无法向 Mongoose 查询返回的对象添加新属性
Can't add a new property to an object returned by Mongoose query
我正在使用Node.js,MongoDB和Express编写API。我似乎无法向我正在迭代的位置对象添加新属性。
我根本不明白我的代码的问题。 loc
是一个普通对象,它应该可以工作。我错了吗?
// **********************************
// GET Locations
// **********************************
// Create endpoint /api/locations for GET
exports.getLocations = function(req, res) {
// Use the Location model to find all locations
// of a particular user
Location.find({}, function(err, locations) {
if (err)
res.send(err);
var counter = 0;
var l = locations.length;
//we create a closure to access the current location object
var closure = function(location) {
//we are returning the callback
return function(err, user) {
if (err)
res.send(err);
counter++;
console.log("The location object: 'n"+location+"'n'n");
console.log("The value we want to add to the object: 'n"+user.username+"'n'n");
//THAT DOESN'T WORK
location.username = user.username;
console.log("The updated object: 'n"+location+"'n'n");
if(counter === l) res.json(locations);
};
};
//We respond with the locations
for (var i = 0; i < l; i++) {
//we call our function
User.findById(locations[i].userId, "username", closure(locations[i]));
}
});
};
这是我在控制台中获得的输出...这太奇怪了。
The location object:
{ _id: 54c65c665ff13962b6a367a1,
userId: '54c659ba8ac00324b617f3f9',
message: 'Big party here tonight!!',
longitude: 45.5,
latitude: 73.5667,
__v: 0 }
The value we want to add to the object:
test123
The updated object:
{ _id: 54c65c665ff13962b6a367a1,
userId: '54c659ba8ac00324b617f3f9',
message: 'Big party here tonight!!',
longitude: 45.5,
latitude: 73.5667,
__v: 0 }
在我们的例子中,你MongooseDocument
没有plain
JS对象。为了获得plain
JS对象,您应该使用这样的.lean
Location.find({}).lean().exec(function(err, locations) {
...
});
相关文章:
- chart.js 2.0为数据集添加了新属性
- 为for循环中的对象添加新属性
- 调用ko.applyBindings后,向Knockout视图模型添加新属性
- 如何向JSON数组添加新属性
- 在对象上迭代并添加新属性
- 在knocket js中应用绑定后,向视图模型添加新属性
- 如何在 CKEditor 表的单元格属性中添加新属性
- 无法向 Mongoose 查询返回的对象添加新属性
- 有没有办法让 Javascript 在将新属性添加到给定对象时抛出错误
- 是否可以向现有 JSON 数据添加新属性
- 使用 contructor 参数将新属性添加到原型
- 和服:修改数据、分解字符串和添加新属性的功能
- 如何将自定义属性添加到 HTML 环境,该属性将默认为元素的每个新实例上的空对象
- 何时使用“原型”一词向 javascript 中的对象添加新属性
- 我的 JS 对象迭代在添加新属性时中断
- Internet Explorer 会自动将高度和宽度属性添加到新追加的图像中
- 使用ECMA脚本向节点(页面)添加新属性
- 无法向对象添加新属性
- 将属性添加到所有新创建的元素
- 在兄弟对象的现有属性的基础上,将新属性添加到javascript对象中