tom*_*456 4 mongoose node.js express
我的POST
一个用户反对我的后端,我希望能够使用 Mongoose 将该用户直接保存到我的数据库中。
但是,如果我为一个对象分配一个新模型,它会覆盖 save 方法。
例如
var user = new User();
user = req.body.user //save no longer available
user.save(function(err){
...
}
Run Code Online (Sandbox Code Playgroud)
有没有办法克服这个问题,因为目前我必须将用户的每个字段分配给模型,如下所示:
var user = new User();
user.email = req.body.user.email;
user.name = req.body.user.name;
...
Run Code Online (Sandbox Code Playgroud)
您正在为变量重新分配user
值req.body.user
,因此您最初分配的新模型将被丢弃。
var foo = 'first'; // declares foo and assigns 'first' to it
foo = 'second'; // reassigns foo with value 'second'
var user = new User(); // declares user and assigns a new User model instance
user = req.body.user // reassigns user with value from req.body.user
Run Code Online (Sandbox Code Playgroud)
您可以将该值传递给 User 模型构造函数,这将实现您想要的结果:
var user = new User(req.body.user); // declares user and assigns a new User model with req.body.user as the initial value
user.save(function(err){
...
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2022 次 |
最近记录: |