使用Mongoose for Node.js在Mongo文档的子数组中推送JSON

时间:2018-12-21 11:51:38

标签: javascript node.js mongoose mongoose-schema

我有一个NodeJS应用程序,在其中我使用了mongoose库与mongo数据库进行通信。

该应用程序是关于一个游戏,其中进行了多个回合。在每一轮之后,将提交轮次结果!我希望将值(一个json)推送到players.rounds。我有一个_id和一个players.id来确定往哪里推。

这是我认为正确的方法(而且我仍然是猫鼬的新手)。它不会显示任何错误,但是db文档不会受到影响。 players.rounds中仍为零。

这是我认为正确的方法(而且我仍然是猫鼬的新手)。

我的猫鼬模式:

const gameSchema = new mongoose.Schema(
    {
        categories: [
            { type: String }
        ],
        countdown: Number,
        players: [{
            _id: false,
            id: String,
            rounds: [
                { type: Map, of: String }
            ],
            score: { type: Number, default: 0 },
            ready: { type: Boolean, default: false }
        }]
    }
);    

我执行的地方:

Game.findOneAndUpdate(
    { _id: gameId, 'players.id': client.id },
    { $push: { 'players.$.rounds': values } }, function(err) {
    if (err) {
        console.log('ERROR when submitting round');
        console.log(err);
    }
});

它不会显示任何错误,但是db文档不会受到影响。 players.rounds中仍为零。

1 个答案:

答案 0 :(得分:0)

您需要更改架构对象。我们需要指定{strict: false}来更改插入的猫鼬文件。

const gameSchema = new mongoose.Schema(
{
    categories: [
        { type: String }
    ],
    countdown: Number,
    players: [{
        _id: false,
        id: String,
        rounds: [
            { type: Map, of: String }
        ],
        score: { type: Number, default: 0 },
        ready: { type: Boolean, default: false }
    }]
}, {strict:false} );