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;
Let's say you are trying to query all the users in your database, you can simply use js map function to do the job for you
Here is an example of what I'm saying
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
})
})
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With