Wednesday, 26 April 2017

Query : get a list of object by reference

I'm using Mongoose to query my database (I'm a beginner). I have 2 schemes :

// Object1
var object1Schema = new Schema ({
    object2List: [{ type : ObjectId, ref : 'Object2'}],
});

// Object2
var object2Schema = new Schema ({
    object1List: [{ type : ObjectId, ref : 'Object1'}],
});

What I want is a function with one argument : - the ID of the object 1

The function have to retrieve the list of Object 2 for the requested ID.

I did something like :

getObjects2ForObject1(object1_ID) {
     var Object2 = mongoose.model('Object2');
     Object2
     .find({'Object1List' : {"$in" : [object1_ID]} } )
     .exec(function (err, object2List) {
         if(object2List.length == 0) {
             console.log("No objects found for this ID");
         }
         else {
             console.log("Objects found");
         }
     }
}

It returns always "No objects found for this ID", but I have checked my database, the list shouldn't be empty.

My query is probably wrong, can someone help me ?

Thanks



via AnthonyR

No comments:

Post a Comment