Sashi
Sashi

Reputation: 135

Data model reference using ObjectID in Mongoose

I have two mongoose models users and requests. One user can have multiple requests. To link these two data models, I am referencing the objectID of the user in the Request model. However when I am trying to fetch all the requests for a particular user ID, I don't get any result.

Users

    var UserSchema = new Schema({
      name: String,
      username: String
    });
module.exports = mongoose.model('User', UserSchema);

Requests

var RequestSchema = new Schema({
  type: String,
  user_id: { type : mongoose.Schema.Types.ObjectId, ref: 'User'}
});
module.exports = mongoose.model('Request', RequestSchema);

Below is the sample code which fetches the requests based on the User ID passed in the URL

exports.getRequests = function (req, res, next) {
      var userId = req.params.id;
      console.log('USER ID'+userId);

      Request.findOne({'user_id': 'kenan'}, function (err, request) {
        if (err) return next(err);
        if (!requests){
            console.log('NO REQUEST FOUND');
            return res.send(401);
        }
        res.json(request);
      });
};

I know I am using findOne which will return me a single resource. However this is failing and I am not getting any result. I have in my DB the data populated. Below is the URL for fetching the requests.

http://localhost:9000/api/V1/users/547ee1e82e47bb982e36e433/requests

Please help suggest as to what I am doing wrong over here.

Thanks

Upvotes: 1

Views: 3010

Answers (2)

Sashi
Sashi

Reputation: 135

OK, the above answer is correct and thanks for your response. I incorrectly populated my Requests collection. This is just for every one's else knowledge. When you have a Object ID reference as one of the fields in the collection then make sure that you are inserting the ObjectID object instead of just the numerical value.

Wrong

{ "_id" : ObjectId("54803ae43b73bd8428269da3"), "user_id" : "547ee1e82e
47bb982e36e433", "name" : "Test", "service_type" : "test", "version" : "10"
, "environment" : "test", "status" : "OK", "__v" : 0 }

Correct

{ "_id" : ObjectId("54803ae43b73bd8428269da3"), "user_id" : ObjectId("547ee1e82e
47bb982e36e433"), "name" : "test", "service_type" : "test", "version" : "10"
, "environment" : "test", "status" : "OK", "__v" : 0 }

Upvotes: 1

BatScream
BatScream

Reputation: 19700

You need to populate the references to the users once you do a find().

  • Once you find all the requests, you need to resolve the references to the users. Use populate to resolve the references.
  • After resolving, filter the requests based on the name that you are searching for.

Updated Code:

Request
.find().populate({'path':'user_id',match:{'name':'kenan'}})
.exec(function (err, resp) {
  var result = resp.filter(function(i){
    return i.user_id != null;
  });
 console.log(result);
})

Upvotes: 1

Related Questions