node.js - 在 Mongoose 中迭代集合的最简单方法

标签 node.js mongodb mongoose

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

'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/

相关文章:

javascript - Firestore - 获取大量集合并进行解析。请求被中止

javascript - 当未处理的 promise 拒绝错误时,nodejs 不断加载

node.js - Node.js 数据集中的最近邻居

node.js - 使用或不使用 'new' 关键字创建 Mongoose 模式?

node.js - Mongoose 查询中是否有相当于 Promise.all 的东西?

javascript - Syncano 对多个字段进行条件过滤

node.js - 在 Node.js 应用程序中组织 View 文件

spring - bean 实例化失败 : Specified class is an interface

node.js - 蒙戈没有数据

node.js - MongoDB/Mongoose 索引使查询更快还是变慢?