I have a document being returned with mongo's findOne(). Inside that document (with a location id of 2), we have items array. Inside items are nicenames. Currently, this returns all items and not just the one where nicename has a match. Thanks!
Menu.findOne({location:'2', 'items.nicename':req.params.whatever}).exec()
.then(function(item) {
res.render('pages/menuitem', {'item':item});
}).catch(function(err) {
console.log(err);
});
I have a document being returned with mongo's findOne(). Inside that document (with a location id of 2), we have items array. Inside items are nicenames. Currently, this returns all items and not just the one where nicename has a match. Thanks!
Menu.findOne({location:'2', 'items.nicename':req.params.whatever}).exec()
.then(function(item) {
res.render('pages/menuitem', {'item':item});
}).catch(function(err) {
console.log(err);
});
Share
Improve this question
asked Feb 22, 2017 at 23:19
webwrkswebwrks
11.9k5 gold badges26 silver badges21 bronze badges
1 Answer
Reset to default 6Mongo find/findOne/aggregate returns the whole document, including sub documents, when your parameters hit a match. So you need to tell Mongo, hey now that you found my document I really only want these parts. That's where a "projection" es in.
Menu.findOne({location:'2'},{'items':{$elemMatch: {'nicename': req.params.whatever})
The thing about projections is once you start building one you need to tell mongo all of the keys you want returned. For example, I know your structure has "location" in it so if you want location returned as well you need to do the following
Menu.findOne({location:'2'},{
'location':1,
'items':{$elemMatch: {'nicename': req.params.whatever}
})
If you need both parameters in the findOne do the following
Menu.findOne({location:'2','items.nicename':req.params.whatever},{
'location':1,
'items':{$elemMatch: {'nicename': req.params.whatever}
})