【问题标题】:How to update a collection document using multiple criteria如何使用多个条件更新集合文档
【发布时间】:2018-06-02 19:37:14
【问题描述】:

我在“registosSRS”集合中有此文档:

{
    "_id" : ObjectId("5a3a2b47d04b7e07f8a273dc"),
    "sessao" : "5",
    "valorRelacao" : "4.89",
    "valorObjectivo" : "4.97",
    "valorAbordagem" : "4.88",
    "valorGeral" : "4.92",
    "cliente_id" : "5a1407c8099ca208e48170a5",
    "email" : "mgoncalves@psi.uminho.pt",
    "data" : 1513761607431
}

此文档收藏在sessao 中。我在另一个地方创建了这个文档,并将 dadosSRS 设置为 {},因为我想稍后更改这个值。是否可以在不创建此值的情况下添加它?

"_id" : ObjectId("5a3a2b41d04b7e07f8a273db"),
"cliente" : ObjectId("5a1407c8099ca208e48170a5"),
"data" : 1513761601705,
"numero" : "5",
"dadosORS" : ObjectId("5a3a2b41d04b7e07f8a273da"),
"dadosSRS" : {
} 

然后我在集合 sessao 中查找客户端和编号 os 会话,就像在 registosSRS 中一样,以添加 registosSRS id。

mongoClient.collection('sessao', function(err,collection){
 collection.update(                                                      
  {cliente:result.cliente_id, numero:dadosSRS.sessao},
   {$set: {'dadosSRS':dadosSessao.dadosSRS}},
      function(result){
      if (err) throw err;
      console.log(result);
      console.log('encontrou registo do cliente na collection registoSRS: ' + result);
    });

但结果为空,虽然我有客户端和会话号。我做错了什么?

【问题讨论】:

  • 是sessao。对不起。
  • 您的查询可能有问题。你可以尝试运行这样的东西吗:db.sessao.findOne({cliente:"5a3a2b47d04b7e07f8a273dc"}, function(err, result{ console.log(result) }});
  • 我在节点上做过,mongoClient.collection('sessao', function(err,collection){ collection.findOne({cliente:"5a3a2b47d04b7e07f8a273dc"}, function(err, result){ console.log ('result' + result) } ); 但结果仍然为空。你想让我在 mongo shell 中做吗?
  • 您需要先将字符串转换为ObjectId,然后才能在查询中使用它,如answer
  • 如果我这样做 db.sessao.findOne({cliente:ObjectId("5a1407c8099ca208e48170a5")});它返回对象

标签: node.js mongodb


【解决方案1】:

在您的回调中,您只有一个参数,它本质上是错误对象,因此结果为 null,因为更新选项没有引发错误。您需要返回实际结果对象的第二个参数。您使用了错误的更新方法,如果命令执行成功,则返回结果对象,而不是实际的文档。

documentation 开始,结果对象具有以下属性:

Name            Type            Description
result          Object          The raw result returned from MongoDB, field will vary depending on server version.
                                Properties

                                Name        Type    Description
                                ok          Number  Is 1 if the command executed correctly.
                                n           Number  The total count of documents scanned.
                                nModified   Number  The total count of documents modified.

connection      Object          The connection object used for the operation.
matchedCount    Number          The number of documents that matched the filter.
modifiedCount   Number          The number of documents that were modified.
upsertedCount   Number          The number of documents upserted.
upsertedId      Object          The upserted id.

您需要使用 findOneAndUpdate,如果找到,它将返回更新的文档

const { ObjectId } = require('mongodb'); // or ObjectID 
// or var ObjectId = require('mongodb').ObjectId if node version < 6
const safeObjectId = s => ObjectId.isValid(s) ? new ObjectId(s) : null;


collection.findOneAndUpdate(                                                  
    { 'cliente': safeObjectId(result.cliente_id), 'numero': dadosSRS.sessao },
    { '$set': { 'dadosSRS': dadosSessao.dadosSRS } },
    { 'returnOriginal': true },
    function(err, result) { // <-- add result as a second argument in the callback
        if (err) throw err;
        console.log(result);
        console.log('encontrou registo do cliente na collection registoSRS: ' + result);
    });

【讨论】:

  • 它也返回 null。
  • 我可以比较像这样的 ObjectId 'cliente':result.cliente_id 吗?
  • 如果result.client_id 是一个字符串,您需要先将其转换为ObjectId,以便您可以在查询中使用它,就像在此answer 中所做的那样。
  • 只是一个注释。这里的结果仍然是空,但是当我访问 mongo shell 并找到文档时,它被更新了。
  • 你的 MongoDB node.js 驱动版本是多少?
猜你喜欢
  • 2020-03-18
  • 2017-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多