猫鼬不会更新数据库中的数组

时间:2018-10-06 16:09:56

标签: arrays node.js database mongodb 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中检查了很多次,并且从未更新过。

1 个答案:

答案 0 :(得分:0)

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