Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo DB Document only returns with "_id" that has "$oid"

I'm trying a very simple CRUD API with the MEAN stack. I entered several documents into a mongolab sandbox db. I could do a GET on all documents and they would all be returned. Then I tested GET by ID:

router.route('/api/v1/resources/:resource_id')

// get the resource with that id (accessed at GET http://localhost:8080/api/resources/:resource_id)
.get(function(req, res) {
    Resource.findById(req.params.resource_id, function(err, resources) {
        if (err)
            res.send(err);
        res.json(resources);
    });
});

And it simply wouldn't work. I kept getting null. But the document existed. I could see it when I would do a GET on all documents.

Then I got another document to return, finally.

The difference? The record that returned had an id in this format:

{
  "_id": { "$oid":"1234567890abc"}
}

But records that did not return had this:

{
   "_id": "1234567890abc"
}

Can Anyone explain this to me? I entered the data with Postman and I didn't do anything different between the entries.

What is $oid? What creates the $oid? Why does that nesting matter for mongoose's findById()?

Thanks!

like image 854
user3730529 Avatar asked Aug 15 '15 19:08

user3730529


1 Answers

$oid is from Strict MongoDB Extended JSON.

All your queries to MongoDB database that contains _id conditions should wrap _id in ObjectId function like the following:

db.resources.findOne({_id: ObjectId("507c35dd8fada716c89d0013")}; 

MongoLab provides UI for querying to MongoDB via JSON syntax. But you can't use ObjectId in JSON due specification restrictions.

So, MongoLab uses Strict MongoDB Extended JSON for alias ObjectId() -> $oid.

{"_id": {"$oid":"507c35dd8fada716c89d0013"})

Same $oid you see in the output because MongoLab UI uses JSON also.

Mongoose automatically converts a string _id to MongoDB query so you don't need doing it manually. The following queries are equivalent:

Resource.findById("507c35dd8fada716c89d0013");
Resource.findById(new mongoose.Types.ObjectId("507c35dd8fada716c89d0013"));
like image 152
Artem Baranovskii Avatar answered Nov 15 '22 06:11

Artem Baranovskii