【问题标题】:mongoose push result to array [duplicate]猫鼬将结果推送到数组[重复]
【发布时间】:2017-10-03 06:07:40
【问题描述】:

我试图通过使用猫鼬“findOne”在 for 循环中从我的 MongoDB 获取结果,然后将结果推送到数组中。找到的结果总是正确的,但它不会把它推到我的数组中,它一直是空的。我用 Promise 尝试过,所以在 findOne 之后使用 then 之类的

Company.findOne().exec(...).then(function(val){
    //here comes then the push function
});

但这也返回了一个空数组。现在我的代码如下所示:

var Company = require('../app/models/company');


function findAllComps(){
    var complist = [];

    for (var i = 0, l = req.user.companies.length; i < l; i++) {
        var compid = req.user.companies[i];

        Company.findOne({id: compid}, function(err, company){
            if(err)
                return console.log(err);

            if (company !== null)
                //result is an object
                complist.push(company);
        });
    }
    return complist;
}

res.json(findAllComps());

感谢您的帮助:)

【问题讨论】:

  • 使用asyncpromises
  • 它应该是什么样子?正如我所说,我在执行后用“then”尝试过,但也没有用

标签: node.js mongodb mongoose promise


【解决方案1】:

如果req.user.companies 是一个ID 数组,您可以简单地使用$in operator 来查找具有任何ID 的所有公司。

// find all companies with the IDs given
Company.find({ id: { $in: req.user.companies }}, function (err, companies) {
    if (err) return console.log(err);

    // note: you must wait till the callback is called to send back your response
    res.json({ companies: companies });
});

【讨论】:

  • 完美,这对我有用,而且非常简单,谢谢! :)
猜你喜欢
  • 2019-10-13
  • 2019-03-22
  • 2016-02-28
  • 1970-01-01
  • 2018-09-19
  • 1970-01-01
  • 2018-05-10
  • 2016-02-04
相关资源
最近更新 更多