首页 > 解决方案 > 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 中检查过很多次,但从未更新过。

标签: arraysnode.jsdatabasemongodbmongoose

解决方案


最快的方法是使用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' } }
)

推荐阅读