数组推送从mongo db获得的记录

时间:2017-04-01 12:26:09

标签: arrays node.js mongodb express mean-stack

MEAN堆栈中,我试图将从mongo db获取的记录存储在数组中,但我无法将记录存储在数组中。

这是我的代码,我试图将从projectimage获得的记录推送到fulldetails []数组,但它失败了。建议我将mongo db记录存储到数组

的可能解决方案
    var express = require("express"),
     router = express.Router(),
     project = require("../../models/project.js"),
     projectimage = require("../../models/projectimages.js"),

             var details=data;
                 var fulldetails=[];

for (var i = 0; i < details.length; i++) {
    var prjct_id=details[i]._id;
    console.log('below'+i);
    fulldetails.push(details[i]);
    projectimage.findOne({projectId: prjct_id}, function(err, data){
       fulldetails.concat(data);
                   });
    console.log(fulldetails);
       return false;    
}

2 个答案:

答案 0 :(得分:0)

我认为你想要的是从你的Mongo系列中获取一个数组,如果我错了,请纠正我。

我还假设Mongo查询成功运行,并正确返回记录。然后你可以使用toArray函数在回调中获取数组。

// let's say Furniture is your collection
let furniture = Furniture.find({});
let details = [];
furniture.toArray((err, array) => {
  if (err) return; 
  details = array; // now details has your collections' documents
});

有关详情,请参阅this

如果这不是你想要的,请告诉我。

答案 1 :(得分:0)

我认为你正试图获得一整套完整细节。如果我的假设是正确的,你可以在这里尝试我的解决方案:

var fulldetails=[];

for (var i = 0; i < details.length; i++) {

    var prjct_id=details[i]._id;

    projectimage.find({projectId: prjct_id}).toArray(function(err, data){ //convert data to array first
        console.log(data);
        fulldetails.concat(data); // concat data to fulldetails to get a flat array
    });
}
相关问题