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
}
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With