简体   繁体   中英

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

I have a NodeJS application where I use the mongoose library to communicate with my mongo database.

The application is about a game, where multiple rounds are played. And after each round, the results of the round are submitted! I want the values (a json) to be push to players.rounds . I have an _id and a players.id to determine where to push.

This is what I thought would be the right way (and I'm still a newbie in mongoose). It prints me no error, but the db document is not affected. Still zero items in players.rounds .

This is what I thought would be the right way (and I'm still a newbie in 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 }
        }]
    }
);    

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

It prints me no error, but the db document is not affected. Still zero items in players.rounds .

you need to change your schema Object. we need to specify {strict: false} for changing the inserted documents in 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} ); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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