【问题标题】:MongooseJS not saving array correctlyMongooseJS 没有正确保存数组
【发布时间】:2019-07-11 21:34:16
【问题描述】:

我想我在使用 mongoosejs 时遇到了麻烦。我试图将对象数组保持在特定大小为 2。当调用此函数时,它会向数组中添加一个项目,并在必要时将其缩小。但是,当我保存数组时,大小不会减少到 2。按照代码和 cmets。感谢您提供的任何帮助。

 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 在您的架构中是如何定义的?
  • 就像一个数组 "location: []"

标签: javascript node.js mongoose


【解决方案1】:

因为您在架构中定义 location: [],Mongoose 将该字段视为 Mixed,这意味着您必须在更改时通知 Mongoose。请参阅文档here

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

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

【讨论】:

  • 这似乎应该有效,但没有。任何其他想法,或者这可能只是问题的一部分。如果我实际上删除了元素中的第一个数组并保存,然后将一个元素添加到数组中并保存,它的工作时间为 100%。
  • object.markModified('objec_array_property') 为我工作。
猜你喜欢
  • 2014-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-13
  • 1970-01-01
  • 1970-01-01
  • 2022-11-19
相关资源
最近更新 更多