3

私は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.
      }
    });
4

1 に答える 1

8

location: []スキーマで定義しているため、Mongoose はそのフィールドを、Mixed変更したときに Mongoose に通知する必要があることを意味するものとして扱います。こちらのドキュメントを参照してください。

更新するコードを次のように変更しますuser.location

if(user.location.length > 2) {
  user.location.splice(0,1);
  user.markModified('location');
}
于 2012-11-12T20:22:05.407 に答える