How to convert string to ObjectId? Does Mongoose have a constructor?

13,478 views
Skip to first unread message

David D.

unread,
Jul 8, 2011, 12:48:37 PM7/8/11
to Mongoose Node.JS ORM
I've been trying to query an ObjectId that is a value in an embedded
document in an array. The problem is that the query seems to think the
ObjectId is a string. How can I cast or construct an ObjectId from a
string? Schema looks something like this:

var Person = new Schema({
name : {type: String},
stuff : {type: [things]} // an array of Things
});

var Things = new Schema({
name : {type: String},
category : {type: ObjectId} // ObjectId of type in seperate
Categories collection
});


I want to query { stuff.category : ObjectId('...') } so that I can get
all the Person records for a particular category of stuff. And, I'm
trying to build the query from a category ID passed in as a parameter
(note: I'm doing it this way so I can add other query constraints if
necessary)...

var test = {};
test[stuff.category] = req.param('catID');
Person.find(test, function(err, docs) {
...
});

The issue I'm having is that the value is being fed in as a String,
not as an ObjectId, so the query comes back empty. I'm thinking there
has to be a way to set an object as an ObjectId.

So far the only way I've been able to do this is to...

var tempThing = new Thing();
tempThing.category = req.param('catID');
test[stuff.category] = tempThing.category;
Person.find(test, function(err, docs) {
...
});

...but that seems like a poor way to do it. Is there not some way to
do something like this...

test[stuff.category] = ObjectId(req.param('catID'));

Any tips would be greatly appreciated! Thanks!

David D.

unread,
Jul 8, 2011, 2:28:32 PM7/8/11
to Mongoose Node.JS ORM
I actually solved this mere minutes after writing this after spending
a couple hours trying to find the answer. Figures.

Here's how you do it:

var ObjectId = require('mongoose').Types.ObjectId;

then,

test['stuff.category'] = new ObjectId(req.param('catID'));

Solved.
Reply all
Reply to author
Forward
0 new messages