【问题标题】:Using result of one query in another query : nodejs and mongodb在另一个查询中使用一个查询的结果:nodejs 和 mongodb
【发布时间】:2018-09-11 15:09:07
【问题描述】:

我正在尝试计算集合中的文档数,然后使用 Node.js 将结果用于另一个插入查询。

var number;
db.collection("collection").countDocuments({}, function(error, numOfDocs){
    if(error) throw error;
    else{
        console.log(numOfDocs);
        number = numOfDocs;
    }
}); 

var myobj = { num: "Number_"+number };
db.collection("another_collection").insertOne(myobj, function(err, res) 
{
    if (err) throw err;
    console.log("1 document inserted");         
});

集合中插入的值为{ "num" : "Number_undefined" }

如何将第一个查询的结果用于另一个查询?

【问题讨论】:

    标签: node.js mongodb express


    【解决方案1】:

    这是因为你没有给Number一个值。此外,count() 函数是一个异步函数(我为此写了一个答案here)。试试这个:

    db.collection('collection')
      .countDocuments({}, function(error, numOfDocs){
        if(error) throw error;
        else {
            var myobj = { num: 'Number_' + numOfDocs };
            db.collection('another_collection').insertOne(myobj, function(err, res) {
                   if (err) throw err;
                   console.log('1 document inserted');         
            });
        }
    }); 
    

    【讨论】:

    • 谢谢@weirdpanda。但这会产生一个错误“MongoError:服务器实例池被破坏”。知道为什么会这样吗?
    • 不是因为这段代码。你在这之后的某处使用db.close()吗?
    • 谢谢,它成功了。我正在使用 db.close() 删除它,现在它工作正常。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-01
    • 2016-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-08
    相关资源
    最近更新 更多