Many ObjectId objects in Mongoose

My document contains a field called clients , which should contain an array of client identifiers.

 { "first_name":"Nick", "last_name":"Parsons", "email":" nick@movementstrategy.com ", "password":"foo", "clients":[ "50f5e901545cf990c500000f", "50f5e90b545cf990c5000010" ] } 

My data comes in as JSON, and I send it directly to Mongo to create the document. For some reason, clients do not populate when I create, so I need to manually enter them as strings.

My scheme is quite simple and is defined as:

 var userSchema = new Schema({ first_name: { type: String, trim: true }, last_name: { type: String, trim: true }, email: { type: String, trim: true, lowercase: true, index: true, unique: true, required: true }, password: String, clients: [Schema.Types.ObjectId] }); 

From my point of view, I correctly identified customers. But I can not get the array of clients to fill when I do the creation. The event raw object that is passed in mongo looks good.

 { first_name: 'Zack', last_name: 'S', email: ' zack@movementstrategy.com ', password: 'test', clients: [ '50f5e901545cf990c500000f', '50f5e90b545cf990c5000010' ] } 

Is there anything special I have to do with my input so that it runs correctly?

+6
source share
2 answers

Accepted answer may be outdated ...

If you are going to update this collection, I would recommend using the $ push update. This update method is designed to prevent updates when everything you do is added to the array in the collection.

http://docs.mongodb.org/manual/reference/operator/update/push/

+2
source

Simple fix. Checking the filling of the incoming array. If so, I iterate over each of them and insert the converted version of ObjectId into the array. Apparently mongoose.Types.ObjectId('STRING'); can convert a common string to a valid mongoose identifier.

 // if clients was passed with associated client ids if (data.clients.length > 0) { _.map(data.clients, function(cid) { // push client id (converted from string to mongo object id) into clients user.clients.push(mongoose.Types.ObjectId(cid)); }); } 

Hope this helps someone else.

+10
source

All Articles