Node.js:如何使用下划线克隆对象并随后为克隆分配新属性?
我正在使用 Node 和 Express 开发 REST API。我正在使用 mongoose.js,并且正在我的数据库中创建一个新的用户文档。不流汗,效果很好。
当我想向 .save() 返回的 json 对象添加属性时,就会出现问题。我想在保存后添加此属性,因为它是使用 REST 接口的客户端的一个标志,但它不是我想保存到数据库的内容。
这是我的示例:
var _ = require('underscore');
var user = new User({"username" : "Joe"});
user.save(function(err, newuser){
if (err) return next(err);
var nu = _.clone(newuser);
nu.newbie = 'true';
res.send(JSON.stringify(nu));
});
这是一个示例响应(这是 nu
中的内容):
{
"username": "Joe",
"_id": "4f343383a5503c452a000002",
}
如您所见,我正在尝试添加属性 nu.newbie
并将其设置为true
但它不起作用。我认为这是某种范围或参考问题。有什么想法吗?
I'm working on a REST API with node and express. I'm using mongoose.js, and I am creating a new user document in my db. No sweat, works great.
The problem arises when I want to add a property to the json object that the .save() returns. I want to add this property after the save because it's a flag to the client consuming the REST interface, but it's not something I want to save to the db.
Here's my example:
var _ = require('underscore');
var user = new User({"username" : "Joe"});
user.save(function(err, newuser){
if (err) return next(err);
var nu = _.clone(newuser);
nu.newbie = 'true';
res.send(JSON.stringify(nu));
});
Here's an example response (this is what's in nu
) :
{
"username": "Joe",
"_id": "4f343383a5503c452a000002",
}
As you can see, I'm trying to add the property nu.newbie
and set it to true
and it's not working. I believe this is a scope or reference issue of some kind. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题是 save 返回的对象不是“原始”javascript 对象。它被猫鼬包裹着,上面有它的方法。当你克隆时,你也克隆了猫鼬的东西!
当一个 mongoose 对象被 res.send 发送下来时,它会被序列化,并且 mongoose 只序列化它所知道的对象的成员。如果要添加属性,则需要在“原始”JavaScript 对象上执行此操作。像这样:
另外,res.json 只是一个很好的简写,它将负责转换为 json 并设置内容类型。
The issue is that the object returned by save is not a "raw" javascript object. Its wrapped by mongoose and has its methods on there. When you clone, you also clone the mongoose stuff!
When a mongoose object is sent down by res.send, it is serialized, and mongoose only serializes the members of the objects that it is aware of. If you want to add properties, you need to do it on a "raw" javascript object. Like so:
also, res.json is just a nice shorthand that will take care of converting to json and setting the content type.