Sco*_*ott 3 javascript mongoose node.js
我想,我在使用mongoosejs时遇到了麻烦.我试图保持一个特定大小为2的对象数组.当调用此函数时,它会向数组添加一个项目,并在必要时将其缩小.但是,当我保存数组时,大小不会减少到2.遵循代码和注释.感谢您的任何帮助,您可以提供.
user.location.push(req.body); //Add a new object to the array.
if(user.location.length > 2) //If the array is larger than 2
user.location.splice(0,1); //Remove the first item
console.log(user.location); //This outputs exactly what I would expect.
user.save(function(err, updatedUser){
if(err)
next(new Error('Could not save the updated user.'));
else {
res.send(updatedUser); //This outputs the array as if it was never spliced with a size greater than 2.
}
});
Run Code Online (Sandbox Code Playgroud)
因为您location: []在模式中定义,所以Mongoose会对该字段进行处理,Mixed这意味着您必须在更改时通知Mongoose.请参阅此处的文档.
将更新的代码更改user.location为:
if(user.location.length > 2) {
user.location.splice(0,1);
user.markModified('location');
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1833 次 |
| 最近记录: |