简体   繁体   English

猫鼬:将find()结果移动到文件中的数组

[英]Mongoose: moving find() results to an array in the file

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. 然后,我希望能够用数据库中的所有用户填充我的userArr变量,但是即使第一个console.log返回此对象的名称,也不会将其推入数组。 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) 

阵列推送的用法似乎有误,您应按以下方式使用它:

userArr.push(user);

It is because you are using forEach, which is asynchon. 这是因为您使用的是forEach,这是asynchon。 And your push has to be a function 而且您的推送必须是一种功能

userArr.push(yourUser)

Can you try with a "for" like this ? 您可以尝试这样的“ for”吗?

    // 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. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM