2

Say I have this query

var query1 = usersrec.find({username:target}, {});
query1.exec(function (err, docs){
    if(err) throw ;
});

and it gives this result

{ 
    "_id" : ObjectId("5806ba413202e30d68152aa4"), 
    "username" : "sammy", 
    "firstname" : "samuel", 
    "lastname" : "jackson", 
    "gender" : "male", 
    "phone" : "0123456789", 
    "image" : "sam.jpg"
}

I want to add a value which I get from another collection {"Balance" : "1011"} to this resulting document before emitting with socket.io.

I've tried many things and got errors, but this went through without adding the balance key/value:

docs[0].balance = '1011';
console.log(docs);
socket.emit('usernames', docs);

The document still retains its initial values. What am I missing?

chridam
  • 100,957
  • 23
  • 236
  • 235
Willower
  • 1,099
  • 8
  • 22
  • Seems like you are using Mongoose, if so then you need to call the [**`lean()`**](http://mongoosejs.com/docs/api.html#query_Query-lean) method on your query `query1.lean().exec(...)`. This will ensure that documents returned from queries with the lean option enabled are plain javascript objects which you can manipulate and add the other balance property. – chridam Oct 19 '16 at 10:50
  • 2
    @chridam Thanks alot! Worked like a charm. Funny how tiny things you don't know can make a whole difference in code. Thanks! – Willower Oct 19 '16 at 10:53

1 Answers1

0

Seems like you are using Mongoose and Mongoose documents don't allow adding properties. You need to either call the lean() method before exec() since documents returned from queries with the lean option enabled are plain javascript objects:

From the docs:

var query1 = usersrec.find({username:target}, {});
query1.lean().exec(function (err, docs) {
    docs[0] instanceof mongoose.Document // false
});

So your code should look like:

var query1 = usersrec.find({username:target}, {});
query1.lean().exec(function (err, docs){
    if(err) throw ;
    docs[0].balance = '1011';
    console.log(docs);
    socket.emit('usernames', docs);
});

or cast the returned document to a plain object:

var query1 = usersrec.find({username:target}, {});
query1.exec(function (err, docs){
    if(err) throw ;
    docs = docs.map(function(o){ return o.toObject(); });
    docs[0].balance = '1011';
    console.log(docs);
    socket.emit('usernames', docs);
});
chridam
  • 100,957
  • 23
  • 236
  • 235
  • @chrisdam I applied this to a code, and stumbled on another glitch please check it out http://stackoverflow.com/questions/40131084/mongodb-nested-query-returns-only-last-occuring-result – Willower Oct 19 '16 at 12:19