javascriptnode.jsmongodbdbref

Nodejs + mongodb : How to query $ref fields?


I'am using MongoDB with a nodejs REST service which exposes my data stored inside. I have a question about how to interrogate my data which uses $ref.

Here is a sample of an Object which contains a reference to another object (detail) in anther collection :

{
    "_id" : ObjectId("5962c7b53b6a02100a000085"),
    "Title" : "test",
    "detail" : {
        "$ref" : "ObjDetail",
        "$id" : ObjectId("5270c7b11f6a02100a000001")
    },
    "foo" : bar
}

Actually, using Node.js and mongodb module, I do the following :

db.collection("Obj").findOne({"_id" : new ObjectID("5962c7b53b6a02100a000085"},
function(err, item) {
    db.collection(item.$ref).findOne({"_id" : item.$id}, function(err,subItem){
        ...
    });
});

In fact I make 2 queries, and get 2 objects. It's a kind of "lazy loading" (not exactly but almost)

My question is simple : is it possible to retrieve the whole object graph in one query ?

Thank you


Solution

  • Answer of Vladimir is not still valid as the db.dereference method was deleted from MongoDB Nodejs API:

    https://www.mongodb.com/blog/post/introducing-nodejs-mongodb-20-driver

    The db instance object has been simplified. We've removed the following methods:

    db.dereference due to db references being deprecated in the server