如何在mongo节点中执行或调整

时间:2016-09-21 13:07:10

标签: node.js mongodb express

我使用下面的代码执行或调整但是它产生重复,我认为我错了或条件可以有人建议帮助请....

     function get_profile (id, profiles) {

        return new Promise(function (resolve, reject) {
            var requests = db.collection('requests');
            var item = { $or: [ {'sent_id':id}, {'recieved_id':id } ] }
                requests.find( item ).toArray((err, resp) => {
                    if (err) {
                        reject(err)
                        return
                    }
                    if (resp) {
                        profiles.push(resp)
                        resolve()
                    } else {
                        reject()
                    }
                });
        })
    }

}


exports.getprofiledatalistbyid = function(req, res) {
    var params = req.params;
    var record = db.collection('profile');
    record.find().toArray((err, result) => {
        if (err) {
            return
        }
        if (result) {       
            var profiles_to_get = []
            var profiles = []
            for (var i in result) {
                var id = result[i]._id;console.log(id)
                var id = id.toString();
                profiles_to_get.push(get_profile(id, profiles))
                // console.log(profiles_to_get)
            }
            Promise.all(profiles_to_get)
                .then(() => {
                  console.log(profiles_to_get)
                  res.send({status: 'success', data: profiles});
                })
        } //end of if loop
        else {
            response = {
                status: 'fail',
                data: []
            };
        }

    })
    //

我使用下面的代码执行或调整但是它产生重复,我认为我错了或条件可以有人建议帮助请....

1 个答案:

答案 0 :(得分:2)

我怀疑您运行代码时profiles数组不为空。

您将结果推送到数组并解析空承诺而不是使用promise返回数据的任何原因?

我想知道你为什么使用:

profiles.push(resp)
resolve()

而不是:

resolve(resp);

您没有包含使用此承诺的代码,因此无法再说些什么了。只是猜测数组可能在开始时不是空的。

要查看从数据库中获取的内容,您可以使用以下内容记录if (resp) { ... }块内的数据:

console.log(JSON.stringify(resp));

更新

在您的代码的第二部分添加到您的问题后,我更加怀疑。您是否从数据库中获取了所有用户配置文件,然后针对每个用户配置文件搜索包含其sent_idrecieved_id字段中个人资料ID的配置文件?这似乎是对数据库的大量请求。

您可以使用单个请求执行相同的操作,而不是:

{ $or: [ {sent_id: id}, {recieved_id: id } ] }

你使用:

{ $or: [ {sent_id: {$in: ids} }, {recieved_id: {$in: ids} } ] }

其中ids是您想要获取的所有ID的数组。

您可以通过以下方式获取ID列表:

var ids = result.map(i => i._id);

if (result) { ... }区块内的类似内容。

(顺便说一下,你确定你的数据库中的字段被调用" recieved_id"而不是" received_id"?)