【问题标题】:Pushing a JSON in a sub-array of a Mongo document with Mongoose for Node.js使用 Mongoose for Node.js 在 Mongo 文档的子数组中推送 JSON
【发布时间】:2018-12-21 20:50:48
【问题描述】:

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

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

这是我认为正确的方法(我仍然是猫鼬的新手)。它打印我没有错误,但数据库文档不受影响。 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 中的项目仍然为零。

【问题讨论】:

    标签: javascript node.js mongoose mongoose-schema


    【解决方案1】:

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

    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} ); 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-02
      • 1970-01-01
      • 1970-01-01
      • 2020-05-01
      • 2014-04-21
      • 2020-04-02
      相关资源
      最近更新 更多