在mongoose中迭代集合的最简单方法

11

我希望能够遍历一个集合,以便我能够浏览所有的对象。这是我的模式:

'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;
2个回答

15

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

for await (const doc of Model.find()) {
  doc.name = "..."
  await doc.save();
}

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


这是什么黑魔法啊~~~ - Robert Lombardo

13

假设你正在尝试查询数据库中的所有用户,你可以简单地使用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
        })
    })
}

我现在正试图使用它,我可以进入User.find方法,但似乎什么都没有发生。 - Michael Gee

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接