Reputation: 61
I want to get objects whose fields match the query parameters. Here's my document structure:
{
"_id" : ObjectId("606cd605807c6b2b08fe064c"),
"description" : "test",
"shopname" : "MP Auto Parts",
"state" : "Abia",
"lga" : "Aba South",
"address" : "3A Ekpereng street",
"telnum" : "09137700528",
"email" : "[email protected]",
"owner" : "605e8c09c7053d4248935dc4",
"items" : [
{
"_id" : ObjectId("606cdae7de0b153c84bb1d21"),
"vehicletype" : "benz",
"model" : "c class",
"year" : "2020",
"part" : "piston",
"price" : 3000000,
"imageurl" : "https://res.cloudinary.com/xxxxxxxxxxx/image/upload/v1617746664/ghywaik0g1ze6rg6y0pw.jpg",
"imageid" : "ghywaik0g1ze6rg6y0pw",
"createdAt" : ISODate("2021-04-06T22:04:23.906Z"),
"updatedAt" : ISODate("2021-04-06T22:04:23.906Z")
},
{
"_id" : ObjectId("606cd6a7807c6b2b08fe064d"),
"vehicletype" : "honda",
"model" : "acura",
"year" : "2020",
"part" : "door",
"price" : 300000,
"imageurl" : "https://res.cloudinary.com/xxxxxxxxxx/image/upload/v1617745576/mstmrwo6kaxhfibngpew.jpg",
"imageid" : "mstmrwo6kaxhfibngpew",
"createdAt" : ISODate("2021-04-06T21:46:15.274Z"),
"updatedAt" : ISODate("2021-04-06T21:46:15.274Z")
}
],
"createdAt" : ISODate("2021-04-06T21:43:33.499Z"),
"updatedAt" : ISODate("2021-04-06T22:04:23.907Z"),
"__v" : 2
}
Here's my code with select fields option:
Shop.find({}, { vehicletype: vehicletype, model: model, year: year, part: part } )
.where({state: state, lga: city })
.select('vehicletype model year part price imageurl') // Note select option
.exec(function (err, results) {
if (err) {
res.statusCode = 500;
res.setHeader('Content-Type', 'application/json');
res.json(err);
}
console.log('results ', results)
});
It returns only an array of document ids, like:
[
{ _id: 60715a7554b2d70b0c7f84f4 },
{ _id: 607230ef2e9af434a4543a76 }
]
I get close to what i want without the select option:
Shop.find({}, { vehicletype: vehicletype, model: model, year: year, part: part } )
.where({state: state, lga: city })
.exec(function (err, results) {
if (err) {
res.statusCode = 500;
res.setHeader('Content-Type', 'application/json');
res.json(err);
}
console.log('results ', results)
});
Which returns:
[
{
_id: 60715a7554b2d70b0c7f84f4,
vehicletype: 'benz',
model: 'c class',
year: '2020',
part: 'piston'
},
{
_id: 607230ef2e9af434a4543a76,
vehicletype: 'benz',
model: 'c class',
year: '2020',
part: 'piston'
}
]
The ids are those of the document, i want to get the document ids and the entire objects whose fields match my query.
Edit: What i really need in addition to the later code is to have the price and imageurl properties as well.
Upvotes: 1
Views: 565
Reputation: 181
You should be able to do :
Shop.find({ "items.vehicletype": vehicletype, "items.model": model, "items.year": year, "items.part": part, state: state, lga: city } )
.exec(function (err, results) {
if (err) {
res.statusCode = 500;
res.setHeader('Content-Type', 'application/json');
res.json(err);
}
console.log('results ', results)
});
Upvotes: 2