Better way for referencing and derefrencing while querying using mongoskin

47 Views Asked by At

Is there a better way for referencing at the time of creating collection and derefrencing while querying using mongoskin, e.g.

foo collection

Foo: { 
  prop1: true,
  prop2: true,
  bars: [
     {
     "$ref": "Bar",
     "$id": ObjectId("blahblahblah")
     }
  ]
}

bar collection

Bar: {
   testprop: true
}
1

There are 1 best solutions below

0
Sanjaya Dahal On

After couple of days i was able to figure out this. Just want to share it.

Here is the collection say user and group and we want to refer group id to user. `function createUser() {

    var user = _.omit(userParam, 'password');
    var role = _.omit(userParam, 'role');

    grpid.groupId(userParam.role).then(function(id) {
        if (id) {
            console.log(id);
        }
        console.log("No id found")
        user.role = [{ "$ref": "groups", "$id": id }]

        user.hash = bcrypt.hashSync(userParam.password, 10);

        db.users.insert(
            user,
            function(err, doc) {
                if (err) deferred.reject(err.name + ': ' + err.message);

                deferred.resolve();
            });
    })`

For group service

//Function that returns the role id 

function groupId(role) {

//test data
return new Promise((resolve, reject) => {
    db.groups.findOne({ "name": role }, function(err, doc) {
        if (err) {
            reject(err.name + ':' + err.message);
        }
        if (doc) {
            console.log(doc._id);
            resolve({ _id: doc._id });
        }
    })
})

}