D
D
deadkEEper12016-02-26 16:07:25
MongoDB
deadkEEper1, 2016-02-26 16:07:25

How to push an object into an array nested in an object, mongo?

There is a mongo model

var userSchema = new Schema({

    name:{
        required: true,
        type: String
    },
    email:{
        unique: true,
        required: true,
        type: String

    },
    password:{
        required: true,
        type: String
    },

    admin: {
        type: Boolean,
        default: false
    },

    posts: [{
     type: mongoose.Schema.Types.ObjectId,
      ref: 'users'
}],

    friends: {           // object
        incomeRequests:[{   //array in object
            type: mongoose.Schema.Types.ObjectId,
            ref: 'users'
        }],
        outcomeRequests:[{
            type: mongoose.Schema.Types.ObjectId,
            ref: 'users'

        }],
        friends: [{
            type: mongoose.Schema.Types.ObjectId,
            ref: 'users'

        }]
    }
});

If there are no problems with posts
User.update({_id: accountId}, {$push:{'posts':postObj}}, function(err, post){
        if(err){
            console.log(err)
            res.end()
        }else{
            console.log(post)
            res.end()
        }
    });

Then how to push an object into a nested array, say, friends.incomeRequests? Thanks

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
deadkEEper1, 2016-02-27
@deadkEEper1

Everything is simple, it was necessary to do as with ordinary nested arrays
{$push:{'friends.incomeRequests':obj}}

W
werw, 2016-02-26
@werw

{"$push": {array field name: new array element to be added}}
Works great with findAndModify

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question