0

I want to push elements of array to create subdocument,

my schema

var chatGroup = new Schema({

name : {
    type : String,
    default : null 
},
members: {
    type : [subSchemaForMember]
},

}, { collection: 'chatGroup' });

var subSchemaForMember = new Schema({

user_id   : {type : Schema.Types.ObjectId , ref : 'user'}},{_id : false});

my query to save document is

var chatGroup = new ChatGroup({

        name       : req.body.name,
        image      : req.body.image,
        created_by : req.body.celebrity_id,
        $pushAll   : {'members' : req.body.members}
    })

where req.body.memebers = ['someid','someid','someid']

Please help I want to do it without any loop

3
  • is subSchemaForMembers just a string? That's what you're representing at least when you say that req.body.members = ['someId', 'someId', 'someId']? Commented Oct 31, 2017 at 13:57
  • in other words, is it members: { type: [String] } ? Commented Oct 31, 2017 at 13:58
  • members : [{ user_id : {type : Schema.Types.ObjectId , ref : 'user'} ,}] its like this subdocument Commented Oct 31, 2017 at 14:02

1 Answer 1

1

I don't see you actually saving the document, only calling new on the constructor. You need to explicitly call save. on the object after you construct it. For the documentation on creating documents, see here: http://mongoosejs.com/docs/models.html.

Also, the use of $pushAll only applies when you have an object already in mongodb, which has existing values, and you want to retain those values and push additional values onto the array (so in your example you can simply assign the array to members).

Also of note is that the current mongoose documentation indicates that $pushAll is deprecated and you should be using $push together with $each, but the same rules apply, see here:

https://docs.mongodb.com/manual/reference/operator/update/push/#append-multiple-values-to-an-array

Sign up to request clarification or add additional context in comments.

1 Comment

Are you saving the model? Your example doesnt do that, and as i said im not sure you should use push at all on a new object. Just assign the array of ids.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.