Last Updated
Viewed 23 Times
let userSchema = new Schema({
    email: {type: String, required: true},
    password: {type: String, required: true},
    name:  {type: String, required: true},
    phoneNumber: {type: Number, required: true},
    schedule: {type: String, required: true},
    courses: {type: Array, required: false}

I have this condition, my problem is how to add a new course to courses property but in my case course is an another object. I could update using updateOne method, but it changed 1 item but not another.

This question already has an answer here:

I'm coding an API with Node.js, MongoDB and Express. I can't seem to add a new property to the location objects I'm iterating through.

I don't understand the issue with my code at all. loc is a plain object, it should work. Am I wrong?

// **********************************
// GET Locations
// **********************************
// Create endpoint /api/locations for GET

exports.getLocations = function(req, res) {

    // Use the Location model to find all locations
    // of a particular user

    Location.find({}, function(err, locations) {
        if (err)
        var counter = 0;
        var l = locations.length;

        //we create a closure to access the current location object
        var closure = function(location) {

             //we are returning the callback
             return function(err, user) {
                if (err)
                console.log("The location object: \n"+location+"\n\n");

                console.log("The value we want to add to the object: \n"+user.username+"\n\n");

                //THAT DOESN'T WORK
                location.username = user.username;

                console.log("The updated object: \n"+location+"\n\n");

                if(counter === l) res.json(locations);

        //We respond with the locations
        for (var i = 0; i < l; i++) {

            //we call our function
            User.findById(locations[i].userId, "username", closure(locations[i]));

Here's the output I get in the console... This is so weird.

The location object:
{ _id: 54c65c665ff13962b6a367a1,
  userId: '54c659ba8ac00324b617f3f9',
  message: 'Big party here tonight!!',
  longitude: 45.5,
  latitude: 73.5667,
  __v: 0 }

The value we want to add to the object:

The updated object:
{ _id: 54c65c665ff13962b6a367a1,
  userId: '54c659ba8ac00324b617f3f9',
  message: 'Big party here tonight!!',
  longitude: 45.5,
  latitude: 73.5667,
  __v: 0 }

I keep getting the following error when I push a new comment document into a story collection in Mongoose:

[MongoError: The field 'comments' must be an array but is of type Object in document {_id: ObjectId('55d2429477da83b6f593ce53')}]
  name: 'MongoError',
  message: 'The field \'comments\' must be an array but is of type Object in document {_id: ObjectId(\'55d2429477da83b6f593ce53\')}',
  driver: true,
  index: 0,
  code: 16837,
  errmsg: 'The field \'comments\' must be an array but is of type Object in document {_id: ObjectId(\'55d2429477da83b6f593ce53\')}' 

This is my model:

var commentSchema = new Schema({
    text: String,
    date: { type: Date, default: },
    author: String  
var storySchema = new Schema({
    title: String,
    link: String,
    comments: [commentSchema],
    author: String,
    date: { type: Date, default: }

This is my query:'/news/:id/comment', function(req, res) {
    console.log('Hi Received');
    var comment = {
        "author": 'Steven',
        "text": req.body.comment
    Story.findOne({_id:}, function(err, data) {
        if(err) throw err;
        data.comments.push(comment);, data){
            if (err) console.log(err);

I've tried Googling the solution but still can't fix the error.


The collection that I want to add to currently looks like this:

> db.stories.find().pretty()
    "_id" : ObjectId("55d2429477da83b6f593ce53"),
    "author" : "Steven Chen",
    "link" : "AS",
    "title" : "AS",
    "date" : ISODate("2015-08-17T20:22:44.271Z"),
    "comments" : {
         "author" : "Steven",
         "text" : "Alsawdksada"
    "__v" : 0
app.get('/calculatePrice', function(req, res) {
  let toyIds =,
    qty = req.query.qty,
    totalPrice = 0,
    subtotal = 0,
    result = {"items": [], "totalPrice": totalPrice},
    item = {};

    for (let i = 0; i < toyIds.length; i++) {
        Toy.findOne({id: toyIds[0]}, { id: 1, price: 1, _id: 0 }, function(err, toy) {
        if (toy) {
            item[item] =; //doesnt work
            item[qty] = qty[0]; //doesnt work
            item[subtotal] = (toy.price * Number(qty[0])); //doesnt work
            totalPrice += item[subtotal]; //doesnt work


I am trying to find specific toys inside mongodb by their respective ToyIds provided by the url "/calculateprice?id[0]=1234&qty[0]=2&id[1]=1235&qty[1]=1&id[2]=1236&qty[2]=5".

However, after it finds one, I cant seem to use the data to add values to my "item" object properties.

I have done some research and I am guessing it has to do with Toy.findOne being async but I really don't understand and can't seem to figure out a solution myself. Help and explaination to a noob learning node/mongodb would be much appreciated!

Similar Question 4 (3 solutions) : How to remove __proto__ property from a JSON object?

Similar Question 5 (1 solutions) : Updating/deleting mongoose object property

Similar Question 6 (1 solutions) : Update object in array of Mongoose model

Similar Question 9 (1 solutions) : Javascript new object field not saved