Reputation: 105
I created a module that contains a mongoose model (user) that I want to export. For now, this only contains properties name and age.
var mongoose = require('mongoose');
var db = mongoose.createConnection('localhost', 'moviemeter');
var schema = mongoose.Schema({name:String, age: Number});
var User = db.model('user', schema);
module.exports = User;
Here, I would like to acces this model and find all the objects in it. Then, I would like to be able to fill my userArr variable with all the users in my database, but even though the first console.log returns the name of this object it doesn't push it into the array. What's the reason for this and what is a way I can fix this?
// user module
var User = require('./modelModules/memberModel');
var userArr = [];
var users = User.find({}, function (err, users) {
console.log(users[0].name)
users.forEach(function(user) {
userArr.push = user;
});
});
console.log(userArr[0].name)
Upvotes: 0
Views: 68
Reputation: 496
It seems wrong usage of array push, you should use it as following:
userArr.push(user);
Upvotes: 1
Reputation: 2743
It is because you are using forEach, which is asynchon. And your push has to be a function
userArr.push(yourUser)
Can you try with a "for" like this ?
// user module
var User = require('./modelModules/memberModel');
var userArr = [];
User.find({}, function (err, users) {
console.log(users[0].name)
users.forEach(function(user) {
for (var i = 0; i < users.length; i++) {
userArr.push(user);
}
console.log(userArr[0].name);
});
Hope it helps.
Upvotes: 0