Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The easiest way to iterate through a collection in mongoose

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;
like image 684
Michael Gee Avatar asked Dec 10 '22 10:12

Michael Gee


2 Answers

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
        })
    })
}
like image 111
Mo Hajr Avatar answered Mar 06 '23 22:03

Mo Hajr


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.

like image 31
Derek Hill Avatar answered Mar 06 '23 23:03

Derek Hill