我希望能够遍历集合,以便能够遍历所有对象。这是我的架构:
'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;
最佳答案
Mongoose 现在有 async iterators 。这些的优点是在开始迭代之前不需要加载集合中的所有文档:
for await (const doc of Model.find()) {
doc.name = "..."
await doc.save();
}
这是一个great blog post更多详细信息。
关于node.js - 在 Mongoose 中迭代集合的最简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45656257/