1

I have this document in collection "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
}

and this document in collection sessao. I've created this document in another place, and set dadosSRS to {} because I want to later change this value. Is this possible to add this value without having created it?

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

Then I'm looking in collection sessao for a client and number os session as in registosSRS, to add the 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);
    });

but the result is null, although I have the client and the session number. What am I doing wrong?

Alex
  • 21,273
  • 10
  • 61
  • 73
EFO
  • 173
  • 1
  • 10
  • it's sessao. sorry. – EFO Dec 20 '17 at 09:56
  • There is possibly something wrong with your query. Can you try running something like this: `db.sessao.findOne({cliente:"5a3a2b47d04b7e07f8a273dc"}, function(err, result{ console.log(result) }});` – Alex Dec 20 '17 at 10:15
  • I did on node, mongoClient.collection('sessao', function(err,collection){ collection.findOne({cliente:"5a3a2b47d04b7e07f8a273dc"}, function(err, result){ console.log('result' + result) } ); but the result is still null. Do you want me to do in mongo shell? – EFO Dec 20 '17 at 10:20
  • db.sessao.findOne({cliente:"5a3a2b47d04b7e07f8a273dc"}); is null in mongo shell too – EFO Dec 20 '17 at 10:21
  • 1
    You need to convert the string to `ObjectId` first before using it in your query as in this [answer](https://stackoverflow.com/a/21076589/122005) – chridam Dec 20 '17 at 10:22
  • 1
    If I do db.sessao.findOne({cliente:ObjectId("5a1407c8099ca208e48170a5")}); it returns the object – EFO Dec 20 '17 at 10:22
  • Do I convert like this: var ObjectID = require('mongodb').ObjectId; var clienteObjectId = ObjectID(result.cliente); – EFO Dec 20 '17 at 10:23
  • Yes, that is correct @EFO – Alex Dec 20 '17 at 10:32
  • I had to do that safeObjectId to work. Thank you anyway! – EFO Dec 20 '17 at 10:49

1 Answers1

0

In your callback you have only one argument which is essentially the error object hence the result is null since there is no error thrown from the update option. You need a second argument which returns the actual result object. You are using the wrong update method which returns the result object if the command was executed successfully, not the actual document.

From the documentation, the result object has the following properties:

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.

You instead need to use findOneAndUpdate which will return the updated document if found

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);
    });
chridam
  • 100,957
  • 23
  • 236
  • 235
  • it's returning null, too. – EFO Dec 20 '17 at 09:59
  • can I compare to an ObjectId like this 'cliente': result.cliente_id? – EFO Dec 20 '17 at 10:01
  • If `result.client_id` is a string you need to convert it to an `ObjectId` first so that you can use it in your query, as done in this [answer](https://stackoverflow.com/a/21076589/122005). – chridam Dec 20 '17 at 10:17
  • just a note. The result here is still null, but when I access the mongo shell and find the document, it is updated. – EFO Dec 20 '17 at 10:51
  • What's your MongoDB node.js driver version? – chridam Dec 20 '17 at 11:05