[英]Returning empty array in NodeJs using mongoose
I am trying to fill an array with records from a mongoDB database using mongoose. 我正在尝试使用mongoose用mongoDB数据库中的记录填充数组。 When I am trying to fill the records.
当我尝试填写记录时。 It shows an empty array outside the function even though I am declaring the outside the function.
即使我在函数外部声明,它也会在函数外部显示一个空数组。 Below is the code.
下面是代码。
var saveMessageToVariable = function(){
var records = [];
var spark_ids = [];
var obj = new Object();
Message.find().distinct("spark_id").exec(function(err,data) {
data.forEach(function (id) {
if(id != null)
spark_ids.push(id);
});
// console.log(spark_ids.length);
spark_ids.forEach(function(spark_id){
Message.findOne({"spark_id":spark_id}).sort({"date":-1}).exec(function(err,data){
obj.spark_id = data.spark_id;
obj.meesage = data.message;
obj.date = data.date;
obj.message_id = data._id;
records.push(obj);
});
});
});
console.log(records);
}
When I run this, the log is showing an empty array. 当我运行此命令时,日志显示一个空数组。 How do I resolve this issue?
我该如何解决这个问题?
It's an asynchronous call and as soon as data is fetched from database control shifts to next line and therefore prints the initial value, I would prefer you to use a callback like this: 这是一个异步调用,一旦从数据库控件中获取数据并转移到下一行,并因此打印初始值,我希望您使用这样的回调:
function(spark_id,callback){
Message.findOne({"spark_id":spark_id}).sort({"date":-1}).exec(function(err,data){
obj.spark_id = data.spark_id;
obj.meesage = data.message;
obj.date = data.date;
obj.message_id = data._id;
callback(obj);
});
}
function(obj)
{
records.push(obj);
}
You two other approachs for this: 您还有另外两种方法:
1) use try and catch block. 1)使用try and catch块。
2) use async and await keyword. 2)使用async和await关键字。
Cheers! 干杯!
I don't have much experience with moongoose, but according to the docs it supports promises since Version 4. 我对Moongoose的经验并不多,但是根据文档显示,它从版本4开始就支持诺言。
Then this should work: 然后这应该工作:
//I assume you'll need this more often
function notNull(value){ return value != null; }
//returns a promise of the records-Array
var saveMessageToVariable = function(){
//returns a promise of a formated message
function getMessage( spark_id ){
return Message.findOne({ spark_id })
.sort({ date: -1 })
//.exec()
.then( formatMessage )
}
function formatMessage( msg ){
return {
spark_id: msg.spark_id,
message: msg.message,
date: msg.date,
message_id: msg._id
}
}
return Message.find()
.distinct("spark_id")
//.exec()
.then(function( ids ){
//waits for all findOnes to complete, then returns an Array
return Promise.all(
ids.filter( notNull ).map( getMessage )
));
}
I'm not sure, wether you need exec()
in this code or not. 我不确定,是否需要在此代码中使用
exec()
。 You should check that. 您应该检查一下。
//usage
saveMessageToVariable.then(function(records){
console.log(records);
})
btw. 顺便说一句
saveMessageToVariable
doesn't reflect at all what this function does. saveMessageToVariable
完全不反映此功能的作用。 You should choose a better name. 您应该选择一个更好的名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.