findById doesn't seem to work

4,814 views
Skip to first unread message

Marc Harter

unread,
Mar 15, 2011, 11:11:01 AM3/15/11
to mongoo...@googlegroups.com
I have a document that looks like this in mongo:

> db.arcs.find({_id: ObjectId("4d7f7c1462fe764a0a000002")})
{ "_id" : ObjectId("4d7f7c1462fe764a0a000002"), "isoCode" : "ISO-XXX-0000", "userId" : "testarc" }

I am trying to get at it in mongoose with:

Arc.findById("4d7f7c1462fe764a0a000002",function(err,arc){ ... }

And it isn't returning for some reason.  Do I need to put ObjectId("...") around it?  If so, how do I do that?  Or is there something else I'm doing wrong?

Thanks much.
Marc

Marc Harter

unread,
Mar 15, 2011, 11:32:01 AM3/15/11
to mongoo...@googlegroups.com
Finding by id for an embedded document doesn't work either, must be doing something wrong.  Any ideas?

user.contacts.id("4d7f7c1462fe764a0a000002");  // null

Sander Pick

unread,
Mar 15, 2011, 12:07:48 PM3/15/11
to mongoo...@googlegroups.com
i had same issue but the solution is in the docs, last on page: http://mongoosejs.com/docs/embedded-documents.html

Finding an embedded document by id

DocumentArrays have an special method id that filters your embedded documents by their _id property (each embedded document gets one):

Consider the following snippet:

post.comments.id(my_id).remove();
post.save(function (err) {
  // embedded comment with id `my_id` removed!
});

Marc Harter

unread,
Mar 15, 2011, 12:16:13 PM3/15/11
to mongoo...@googlegroups.com
thanks I saw your prev post, the problem is its not finding any using my id (which is an autogenerated ObjectId).  does it need to be wrapped like ObjectId("4d7f7c1462fe764a0a000002")?  If so I haven't found any documentation on how to do that.

Sander Pick

unread,
Mar 15, 2011, 12:29:09 PM3/15/11
to mongoo...@googlegroups.com
I was referring to your question about embedded documents... 

this thread may be of some help regarding the ObjectIds


but for me it works fine if you have a virtual method 'id' and use that for the query like this... 

  MySchema.virtual('id')
    .get(function() {
      return this._id.toHexString();
    });

Aaron Heckmann

unread,
Mar 15, 2011, 12:07:56 PM3/15/11
to mongoo...@googlegroups.com
var ObjectId = require('mongoose').Types.ObjectId;
Arc.findById(new ObjectId("asdfasd"), ...

I'm thinking maybe findById should check for hex strings and convert to ObjectId for us.
--
Aaron


Marc Harter

unread,
Mar 15, 2011, 12:31:31 PM3/15/11
to mongoo...@googlegroups.com
Thanks, not a bad idea, had me confused until now.

Aaron Heckmann

unread,
Mar 15, 2011, 12:36:17 PM3/15/11
to mongoo...@googlegroups.com
Hi Marc, try this:

Arc.findById(new ObjectId("4d7f7c1462fe764a0a000002"), function (err, arc) {
   ...
})



On Tue, Mar 15, 2011 at 12:16 PM, Marc Harter <wav...@gmail.com> wrote:
does it need to be wrapped like ObjectId("4d7f7c1462fe764a0a000002")?  If so I haven't found any documentation on how to do that.



--
Aaron


Marc Harter

unread,
Mar 15, 2011, 12:43:48 PM3/15/11
to mongoo...@googlegroups.com

Arc.findById(new ObjectId("4d7f7c1462fe764a0a000002"), function (err, arc) {
   ...
})


This got rid of errors but it just hangs and never executes the callback.  I had this issue when I was just using the hex string as well.  Could that be an issue with my mongodb or something?  Its the same type of thing that is happening here: https://github.com/LearnBoost/mongoose/issues/290.

Thanks again for your help.

Aaron Heckmann

unread,
Mar 15, 2011, 12:44:20 PM3/15/11
to mongoo...@googlegroups.com
Ok I may be crazy but I just added tested using findById directly with a hexString and it worked fine. No need for the ObjectId constructor.

So something else is up. Can you put up a full gist?

On Tue, Mar 15, 2011 at 11:11 AM, Marc Harter <wav...@gmail.com> wrote:



--
Aaron


Marc Harter

unread,
Mar 15, 2011, 1:21:33 PM3/15/11
to mongoo...@googlegroups.com
So it turned out to be that I had an "init" middleware setup that wasn't calling next(), my bad :)  so it was hung there.  Thanks for all your help!

Guillermo Rauch

unread,
Mar 15, 2011, 3:50:13 PM3/15/11
to mongoo...@googlegroups.com
Mongoose does casting all over now.
findById is essentially a findOne with { _id: yourid } so casting should be in place.


On Tue, Mar 15, 2011 at 10:21 AM, Marc Harter <wav...@gmail.com> wrote:
So it turned out to be that I had an "init" middleware setup that wasn't calling next(), my bad :)  so it was hung there.  Thanks for all your help!



--
Guillermo Rauch
http://devthought.com
Message has been deleted

joshchaney

unread,
Apr 4, 2011, 8:08:31 PM4/4/11
to Mongoose Node.JS ORM
I am having the same problem. If I do a 'find' by itself with no
options and inspect the returned object, I can see the _id I am trying
to get in what is returned.. However if I do findById('xxxxxxxxxxxx',
etc) it returns null.

https://gist.github.com/901318

output from terminal running ( node broken.js | grep
4bdd1bac8813f575f8000001 ) below:

Venue: 4bdd1bac8813f575f8000001 => Vagabond Nightclub
4bdd1bac8813f575f8000001 is: null

I am running plain node.js ( v0.4.3 ). Not sure if my model is to
blame, I'm in the process of converting some Sinatra + MongoMapper
code to Node+Express/Mongoose. Still learning the ropes, but I think
I'm set up correctly. I am stumped.

Aaron Heckmann

unread,
Apr 5, 2011, 12:05:13 PM4/5/11
to mongoo...@googlegroups.com
Josh, is an error returned?
--
Aaron


joshchaney

unread,
Apr 5, 2011, 12:45:23 PM4/5/11
to Mongoose Node.JS ORM
No error. Just rewrote the last bit to double check again:

var getPhotosets = function(venue_id) {
var nVenue = mongoose.model('Venues');
nVenue.findOne({ "_id" : venue_id}, function(err, myvenue) {
if (!err) {
console.log(venue_id + ' is: ' + myvenue);
} else {
console.log('Error: ' + err);
}
});
}

Last night I also scrapped the rest of the schema's except for this:

var Venues = new Schema({
name : { type: String }
});

I also exported my hosted DB and restored to my local computer
( thinking it was an issue with mongohq.com, but I'm still having the
same problem. I did notice from the mongod web console that I can see
the query just sitting there:

conn 13 R 2004 mydb.venues { query: { _id:
ObjectId('4bdd1bac8813f575f8000001') } } 127.0.0.1:57063

It goes away when I kill the script with ctrl-c. Should I be closing
the connection some how?

joshchaney

unread,
Apr 7, 2011, 5:42:10 AM4/7/11
to Mongoose Node.JS ORM
Figured out the problem. Sharing in case anyone is doing a conversion
from MongoMapper. Not sure how to fix it at the moment. Apparently
mongomapper ( this was originally a Sinatra/MongoMapper app ) used to
use the string representation of objectId's, rather than an object by
default.

See:
> db.venues.find({})
{ "_id" : "4bda6d338740ed01de000001", "name" : "Sanctum" }

Notice the lack of ObjectId('4bdd1bac8813f575f8000001').

When Mongoose queries for the id, it's doing this:

db.venues{ query: { _id: ObjectId('4bdd1bac8813f575f8000001') }}

which is returning nothing. Doing a find by itself ( not FindById )
with { "_id" : '4bdd1bac8813f575f8000001' } is still forcing the query
for ObjectId('4bdd1bac8813f575f8000001'). Not sure if there is a way
around this. Trying to figure out if I can script a conversion
somehow..
Reply all
Reply to author
Forward
0 new messages