Title: Cannot see a field added on a JSON document with Nodejs and Mongoose
Tags: json;node.js;mongodb;mongoose
Question: if I query MongoDB with a simple query like this using mongoose:
.find()
.where('address.loc').near({ center: [lat,lng], maxDistance: 1 })
.exec(function(err, result) {
if (err) {
request.log(['server', 'database', 'error'], 'An error occured during the execution of the query');
}else{
for(var i=0;i<result.length;++i){
result[i]["distance"] = 5;
console.log(result[0].distance);
console.log(result[0])
The first console.log prints : 5
But the second one prints :
{ address: { loc: [ 37.0814402, 15.287517 ], value: 'viale tica' },
tags: [ 'Primi', 'Secondi' ],
__v: 0,
cap: 96100,
ad_number: 15,
business_email: 'prova@provbhifbvvyvg',
_id: 571b3b78249a2e160b4eee3f }
Why this document and the others in the result array are without the field distance?

Here is the accepted answer: Because result[0] is a mongoose document object. And when you call console.log(result[0]) the result is converted to the string (with mongoose document toString function). But mongoose document doesn't contain distance field.
To do what you want, you should convert each document to object:
var objects = results.forEach(results, function(res) {
res = res.toObject();
res["distance"] = 5;
return res;
console.log(objects[0].distance);
console.log(objects[0]);
http://mongoosejs.com/docs/api.html#document_Document-toObject
Comment for this answer: Thanks. I didn't think about mongoose object.


{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2016:00:04/23/16', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<json><node.js><mongodb><mongoose>', 'Title': 'Cannot see a field added on a JSON document with Nodejs and Mongoose', 'ViewCount': 31, 'id': 36809779, 'user_AboutMe': None, 'user_AccountId': 6445770.0, 'user_DisplayName': 'Graziano Dimatteo', 'user_Reputation': 187.0, 'user_Views': 25.0, 'user_id': 4994325.0}}