MongooseJS不能正确保存数组

我觉得我在用mongoosejs遇到麻烦。 我想保持一个特定的大小为2的对象数组。当这个函数被调用时,它将一个项目添加到数组,并在必要时减less它。 但是,当我保存数组的大小不是修剪到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. } }); 

因为你在模式中定义了location: [] ,所以Mongoose把这个字段视为Mixed ,这意味着当你改变它时你必须通知Mongoose。 看到这里的文档。

将更新user.location的代码更改为:

 if(user.location.length > 2) { user.location.splice(0,1); user.markModified('location'); }