我在收集" 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" : {
}
然后,我在registosSRS中查找集合sessao
以获取客户端和号码会话,以添加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);
});
但结果为null,尽管我有客户端和会话号。我做错了什么?
答案 0 :(得分:0)
在你的回调中,你只有一个基本上是错误对象的参数,因此结果是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);
});