【问题标题】:Mongoose does not update my array in the databaseMongoose 不会更新我在数据库中的数组
【发布时间】:2018-10-06 16:09:55
【问题描述】:

我正在尝试使用 mongoose 更新我的收藏。

这是我的架构:

var FamilySchema = mongoose.Schema({
construction: {
    type: Array,
    default: [
        ["foundry", 0],
        ["farm", 0],
        ["sawmill", 0]
    ]
}
});

这是我的代码:

app.put('/construction/updateConstruction/:id', (req, res) => {
let id = req.params.id;

Family.findById(id, (err, familiaDB) => {

    if (err) {
        return res.status(500).json({
            ok: false,
            err
        });
    }

    if (!familiaDB) {
        return res.status(400).json({
            ok: false,
            err
        });
    }

    // I want to update the value of the posicion 0 in the array.
    familiaDB.construction[0][1] = 1;
    familiaDB.save();
    console.log(familiaDB);

});
});

发出请求后在 console.log 中的结果:

Escuchando puerto:  3000
Base de datos ONLINE

{ state: true,    
construction:
[ [ 'foundry', 1 ],
 [ 'farm', 0 ],
 [ 'sawmill', 0 ],
_id: 5bb8d69c604625211c572ada,
__v: 0 }

在 console.log 中一切都很好并且更新了,但在我的数据库中它没有更新。我在robomongo中检查了很多次,从来没有更新过。

【问题讨论】:

    标签: arrays node.js database mongodb mongoose


    【解决方案1】:

    最快的方法是使用findOneAndUpdate

    Family.findOneAndUpdate(
      { _id: mongoose.Types.ObjectId("YOURID") }, 
      { $set: { 'construction.0.1': 'YourValue'  }}
    )
    

    这将在一个语句中完成。

    现在,您可以使用$elemMatch 来代替按索引执行此操作,并通过以下方式更新正确的:

    Family.findOneAndUpdate(
      {_id: ObjectId("YOURID"), 'cons': { $elemMatch: { '0': 'foundry' }}}, 
      { $set: { 'cons.$.1': 'YourValue' } }
    )
    

    【讨论】:

      猜你喜欢
      • 2020-07-11
      • 2020-12-12
      • 2016-02-05
      • 1970-01-01
      • 2014-08-28
      • 1970-01-01
      • 1970-01-01
      • 2020-07-11
      • 1970-01-01
      相关资源
      最近更新 更多