Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongoose find document by subdocument's _id

Let say I have the following structure:

var Partner = require('../partner/partner.model');

var ContractSchema = new Schema({
      // blahblah
      partners: [Partner.schema]
});

So here every contract has an array of partners, and each partner has an _id property.

I want to search for a contract, which has a partner with a specific _id. I tried this, but didn't work:

  var ObjectId = require('mongoose').Types.ObjectId;    
  Contract.find({
      partners: {
        $elemMatch: {
          _id: {
            $eq: new ObjectId(req.query.partnerId)
          }
        }
      }
    }, function (err, serviceContracts) {
      if (err) {
        return handleError(res, err);
      } else {
        return res.status(200).json(serviceContracts);
      }
    });

EDIT: Here's an example what I have in the db:

{
    "_id" : ObjectId("57e370e72beac9fc21c99ca3"),
    "updatedAt" : ISODate("2016-09-22T05:49:27.000Z"),
    "createdAt" : ISODate("2016-09-22T05:49:27.000Z"),
    "currency" : "USD",
    "partners" : [ 
        {
            "updatedAt" : ISODate("2016-09-22T05:49:27.000Z"),
            "createdAt" : ISODate("2016-09-22T05:49:27.000Z"),
            "name" : "Apple Inc.",
            "_id" : ObjectId("57e370e72beac9fc21c99caa")
        }
    ],
    "__v" : 0
}
like image 696
dnnagy Avatar asked Feb 05 '23 15:02

dnnagy


1 Answers

As @robertklep said, this is working:

Contract.find({ "partners._id": req.query.partnerId})
  .then(function(contracts) {
    return res.status(200).json(contracts);
  })
  .catch(function(err) {
    return handleError(res, err);
  });
like image 184
dnnagy Avatar answered Feb 08 '23 10:02

dnnagy