0

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)
Tijl Declerck
  • 105
  • 1
  • 11
  • This is a classic case – _User.find_ is an asynchronous operation. You need to understand the basic concepts of asynchronous programming. It's not possible to write procedural code as you are trying to do with async. Your options are using Promises or async/await. – Patrick Hund Sep 18 '17 at 14:08
  • Thanks, I'll have a look at those subjects. Could you recommend a good learning resource for this? – Tijl Declerck Sep 18 '17 at 14:18

2 Answers2

1

It seems wrong usage of array push, you should use it as following:

userArr.push(user);
Ninja
  • 486
  • 4
  • 12
0

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.

Sparw
  • 2,688
  • 1
  • 15
  • 34