Search code examples
node.jsarraysjsonmongodbmongoose-schema

How to add an array as different objects mongodb


I'm having some trouble with a post function in nodeJs I have the next body to post:

{
    "_id": "fffff-ggg-jjjjj",
    "type": "",
    "gamers": [
        "Raul Andres",
        "Pedro",
        "Juan"
    ]
}

(I shouldn't change the post body)

And this is my Schema:

var gameSchema = new Schema({
    _id: { 
        type: String,
        required: true,
        trim: true
    },
    type: {
        type: String,
        trim: true
    },
    gamers: [{
        name: { 
            type: String,
            required: true,
            trim: true
        },
        playerBet: {
            type: Number,
            trim: true
        }
    }],
    inProgress: {
        type: Boolean,
        trim: true
    },
}); 

So clearly i can't just give it the gamers just like that, so i need to get the array given in the POST body and insert every element as name field so i can add it in the collection.

expected output

{
 "id": "fffff-ggg-jjjjj",
 "gamers": {
 "5257b4d6-5c87-4871-93c3-b2b9ce04d706": {
 "id": "5257b4d6-5c87-4871-93c3-b2b9ce04d706",
 "name": "Raul Andres"
 },
 "8dda6205-f54c-4643-a017-71b6f0353319": {
 "id": "8dda6205-f54c-4643-a017-71b6f0353319",
 "name": "Juan"
 },
 "e5834d8e-5195-41fc-993e-c731dbce4fab": {
 "id": "e5834d8e-5195-41fc-993e-c731dbce4fab",
 "name": "Pedro"
 }
 },
 "inProgress": false,
 "winner": {
 "id": "e5834d8e-5195-41fc-993e-c731dbce4fab",
 "name": "Pedro"
 }
}
router.post('/createGame', async (request, response, next) => {
    try {
        const { _id, gamers } = request.body;
        const data = new gameModel({
            _id,
            players:{ 
                 name: gamers  
            },
            inProgress: true,
        });
        await data.save();
        response.json({
            message: 'Game created successfully',
            data
        });
    } catch (error) {
        response.status(500).json({
            message: error.message,
            stack: error.stack
        });
    }
});

This is the way i was trying to do it but, name expects a String instead of an array

Thank any who can help me


Solution

  • You can create a gamers schema and add the id to the gamerSchema under the gamers key and store the gamers _id to the gamerSchema.gamers array