我正在使用mongodb缝合/领域,并尝试使用foreach修改数组中的对象,并将ids推送到新的数组中。
对于我正在修改的每个对象,我也首先执行一个查询,在找到文档后,我开始修改对象,然后将id推入另一个数组中,以便以后可以同时使用这两个数组。
代码如下所示:
exports = function(orgLoc_id, data){
var HttpStatus = require('http-status-codes');
// Access DB
const db_name = context.values.get("database").name;
const db = context.services.get("mongodb-atlas").db(db_name);
const orgLocPickupPointCollection = db.collection("organizations.pickup_points");
const orgLocStreamsCollection = db.collection("organizations.streams");
const streamsCollection = db.collection("streams");
let stream_ids = [];
data.forEach(function(stream) {
return streamsCollection.findOne({_id: stream.stream_id}, {type: 1, sizes: 1}).then(res => { //if I comment this query it will push without any problem
if(res) {
let newId = new BSON.ObjectId();
stream._id = newId;
stream.location_id = orgLoc_id;
stream.stream_type = res.type;
stream.unit_price = res.sizes[0].unit_price_dropoff;
stream._created = new Date();
stream._modified = new Date();
stream._active = true;
stream_ids.push(newId);
}
})
})
console.log('stream ids: ' + stream_ids);
//TODO
};但是,当我尝试登录'stream_ids‘时,它是空的,并且什么也没有显示。未分配属性stream_type和unit_price。
我试过许诺,但没有成功
发布于 2020-06-23 06:00:51
这是一个异步问题。在回调中填充数组的值。但由于事件循环的性质,在执行console.log时不可能调用任何回调函数。
你提到了一个涉及承诺的解决方案,这可能是正确的策略。例如,如下所示:
exports = function(orgLoc_id, data) {
// ...
let stream_ids = [];
const promises = data.map(function(stream) {
return streamsCollection.findOne({ _id: stream.stream_id }, { type: 1, sizes: 1 })
.then(res => { //if I comment this query it will push without any problem
if (res) {
let newId = new BSON.ObjectId();
// ...
stream_ids.push(newId);
}
})
})
Promise.all(promises).then(function() {
console.log('stream ids: ' + stream_ids);
//TODO
// any code that needs access to stream_ids should be in here...
});
};请注意将forEach更改为map...that的方式,您将获得一个包含所有promise的数组(我假设您的findOne由于.then而返回promise)。
然后使用Promise.all等待解析所有承诺,然后就应该拥有数组了。
附注:一种更优雅的解决方案是在.then中返回newId。在这种情况下,Promise.all实际上将解析所有promises的结果数组,这将是newId的值。
https://stackoverflow.com/questions/62523967
复制相似问题