My document contains a field called clients that is supposed to contain an array of client id's.
{
  "first_name":"Nick",
  "last_name":"Parsons",
  "email":"[email protected]",
  "password":"foo",
  "clients":[
    "50f5e901545cf990c500000f",
    "50f5e90b545cf990c5000010"
  ]
}
My data is coming in as JSON, and I directly send it to Mongo to create a document. For some reason, clients is not being populated when I create, so I have to manually enter them in as strings.
My schema is fairly simple, and 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 understanding, I've defined clients correctly. But I cannot get the clients array to populate when I am doing the create. Event the raw object that gets passed to mongo looks good.
{ 
    first_name: 'Zack',
    last_name: 'S',
    email: '[email protected]',
    password: 'test',
    clients: [
       '50f5e901545cf990c500000f', 
       '50f5e90b545cf990c5000010' 
    ] 
}
Is there something special that I have to do to my input so that it's casted correctly?
Simple fix. Checking if the incoming array is populated. If so, I loop through each and push a converted ObjectId version into the array. Apparently mongoose.Types.ObjectId('STRING'); is able to convert a general string to a valid mongoose id.
// 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.
The accepted answer may be outdated...
If you're going to update this collection, I would recommend using a $push update. This method of updating is designed to avoid performing updates when all you're doing is appending to an array in the collection.
http://docs.mongodb.org/manual/reference/operator/update/push/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With