The easiest way to iterate through a collection in mongoose

Viewed 13538

I want to be able to iterate through a collection so that I am able to go through all the objects. Here is my schema:

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

Mongoose now has async iterators. These have the advantage of not needing to load all documents in a collection before they start iterating:

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

Here is a great blog post with more details.

Related