4

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
}
6
  • 1
    first of all replace Contract.find({ partner: { with Contract.find({ partners: { Then tell Commented Nov 26, 2016 at 18:39
  • Replaced, still not works.
    – dnnagy
    Commented Nov 26, 2016 at 18:41
  • Can you please give me your one record contract table. Commented Nov 26, 2016 at 18:43
  • @Himanshusharma Added an example.
    – dnnagy
    Commented Nov 26, 2016 at 18:52
  • this works directly in mongo db.a.find({partners:{$elemMatch:{_id:{$eq:ObjectId("57e370e72beac9fc21c99caa")}}}}), you're sure that req.query.partnerId is correct ? Have you tried using directly : _id: req.query.partnerId ?
    – Daphoque
    Commented Nov 26, 2016 at 19:02

1 Answer 1

12

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);
  });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.