2016-04-23 49 views
0

一个JSON文件,如果我查询的MongoDB用一个简单的查询像这样用猫鼬:不能看到现场加与和的NodeJS猫鼬

User 
.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]) 
    } 

}); 

第一的console.log打印:5

但第二个打印:

{ address: { loc: [ 37.0814402, 15.287517 ], value: 'viale tica' }, tags: [ 'Primi', 'Secondi' ], __v: 0, cap: 96100, ad_number: 15, business_email: '[email protected]', _id: 571b3b78249a2e160b4eee3f }

为什么这个文件,结果阵列中的其他人都没有场距离?

回答

1

因为result[0]是一个猫鼬文档对象。当你呼叫console.log(result[0])结果被转换成字符串(用猫鼬文件0​​功能)。但猫鼬文件不包含distance字段。

做你想做什么,你应该将每个文件对象:

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

+0

感谢。我没有考虑猫鼬的物体。 –