2012-11-12 61 views
2

我想mongoosejs有问题。我试图保留一个特定大小为2的对象数组。当调用这个函数时,它会将一个项目添加到数组中,并在必要时将其缩小。但是,当我保存数组时,大小不会缩减为2.请遵循代码和注释。感谢您的任何帮助,您可以提供。MongooseJS不能正确保存数组

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. 
     } 
    }); 
+0

架构中的如何界定'location'? – JohnnyHK

+0

就像一个数组“位置:[]” – Scott

回答

8

因为你定义在模式location: [],猫鼬把该领域作为Mixed这意味着你必须在你已经改变了它通知猫鼬。请参阅文档here

更改您的代码更新user.location是:

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

这似乎应该工作,但没有。任何其他想法,或者这可能只是问题的一部分。如果我实际上删除了元素中的第一个数组并保存,然后将一个元素添加到数组中并保存,它将在100%的时间内运行。 – Scott

+1

'markModified()'为我做了诡计 – tinybyte

+0

object.markModified('objec_array_property')为我工作。 –