Javascript MongooseJS未正确保存数组
我想我和猫鼬之间有麻烦。我试图将对象数组保持为2的特定大小。调用此函数时,它会向数组中添加一个项,并在必要时对其进行精简。但是,当我保存数组时,它的大小并没有减少到2。遵循代码和注释。谢谢你能提供的帮助Javascript MongooseJS未正确保存数组,javascript,node.js,mongoose,Javascript,Node.js,Mongoose,我想我和猫鼬之间有麻烦。我试图将对象数组保持为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.lo
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。见文件
将更新用户位置的代码更改为:
if(user.location.length > 2) {
user.location.splice(0,1);
user.markModified('location');
}
location
在您的模式中是如何定义的?就像数组“location:[]”一样,它似乎应该工作,但没有工作。还有其他想法吗,或者这只是问题的一部分。如果我实际上删除了元素中的第一个数组并保存,然后向数组中添加一个元素并保存,那么它将在100%的时间内工作。