rex
rex

Reputation: 1025

Pushing item to Mongodb collection array

I am trying to push a value to mongodb collection arrayList (user.completed) but it's not getting updated even though my code seems correct.

When I make the API call, the values are being passed however "$push" isn't adding value to completed array!! What am I missing here?

When I try to push to value to a string, I get mongoose error as expected. But when I try to push value to an undefined key ('abc'), a new array doesn't get created like the mongodb documentation suggest! Not sure what is going on here!

// Mongodb Data

{
"_id" : ObjectId("58aa2eb1de7b414237b93981"),
"email" : "[email protected]",
"firstName" : "test",
"completed" : [],
"playing" : [],
"__v" : 2

// API

import mongoose from 'mongoose'
import { Router } from 'express'
import User from './../model/user'

api.put('/completed/:id', (req, res) => {
    User.update(
        { "_id": req.params.id },
        { "$push": { 
             "completed": req.body.completed 
        }}
    )
    .then(doc => res.send(doc), err => res.status(400).send(err))
})

// Request

var request = require("request");

var options = { 
    method: 'PUT',
    url:    'http://localhost:8008/v1/user/completed/58aa2eb1de7b414237b93981',
    headers: { 
        'content-type': 'application/json' },
        body: { completed: { game: 'A', player: 'B' } },
        json: true 
     };

    request(options, function (error, response, body) {
        if (error) throw new Error(error);
        console.log(body);
    });

Upvotes: 0

Views: 558

Answers (2)

parwatcodes
parwatcodes

Reputation: 6798

use $addToSet to stop duplication of same data in the array

$addToSet won't add the item to the given field if it already contains it, but $push will add the given value to field whether it exists or not.

User.update({ "_id": req.params.id  },
    { $addToSet: { "completed": req.body.completed } }, function (err, d) {
        if (!d.nModified) {
           // same value entered won't add to the array
        } else {
            // new value entered and will add to the array
        }
});

Upvotes: 1

rex
rex

Reputation: 1025

Found the issue! I refactored the code but didn't change the user model. I changed 'gamesCompleted' to 'completed' in all places but the user model. Hence, the query failed. I hope, mongoose would give me a better error then just { ok: 0, n: 0, nModified: 0 }

Upvotes: 0

Related Questions