遍历猫鼬集合的最简单方法

Mic*_*Gee 1 mongoose mongodb node.js

我希望能够遍历一个集合,以便能够遍历所有对象。这是我的架构:

'use strict';

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const bcrypt = require('bcrypt');
const moment = require('moment');

//Create user schema 
const UserSchema = new Schema ({
    username: { type: String, unique:true },
    password: {type:String},
    phonenumber: Number,
});

//**************PASSWORD STUFF *******************************
//Hash the password so it becomes encrypted.
UserSchema.methods.generateHash = function(password){
    return bcrypt.hashSync(password,bcrypt.genSaltSync(9));
}

UserSchema.methods.validPassword = function(password){
    return bcrypt.compareSync(password,this.password);
}
//************************************************************

//Schema model.
const User = mongoose.model('user-dodger', UserSchema);

module.exports = User;
Run Code Online (Sandbox Code Playgroud)

Der*_*ill 15

Mongoose 现在有异步迭代器。这些的优点是在开始迭代之前不需要加载集合中的所有文档:

for await (const doc of Model.find()) {
  doc.name = "..."
  await doc.save();
}
Run Code Online (Sandbox Code Playgroud)

这是一篇很棒的博客文章,其中包含更多详细信息。


Moh*_*ajr 6

假设您正在尝试查询数据库中的所有用户,则只需使用js map函数即可为您完成这项工作

这是我在说的一个例子

const queryAllUsers = () => {
    //Where User is you mongoose user model
    User.find({} , (err, users) => {
        if(err) //do something...

        users.map(user => {
            //Do somethign with the user
        })
    })
}
Run Code Online (Sandbox Code Playgroud)