繁体   English   中英

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

[英]Pushing a JSON in a sub-array of a Mongo document with Mongoose for Node.js

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

该应用程序是关于一个游戏,其中玩了多个回合。 在每一轮之后,将提交轮次结果! 我希望将值(json)推送到players.rounds 我有一个_idplayers.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仍然为零。

您需要更改架构对象。 我们需要指定{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} ); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM