我想我在使用 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.
}
});