Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populating array of ObjectId's in Mongoose

Tags:

mongoose

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?

like image 919
Nick Parsons Avatar asked Jan 16 '13 19:01

Nick Parsons


2 Answers

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.

like image 133
Nick Parsons Avatar answered Sep 18 '22 22:09

Nick Parsons


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/

like image 28
Michael Leanos Avatar answered Sep 22 '22 22:09

Michael Leanos