Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo findOne inside of Array

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);
    });
like image 608
webwrks Avatar asked Oct 20 '25 10:10

webwrks


1 Answers

Mongo 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" comes 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}
})
like image 188
Jeff Justice Avatar answered Oct 21 '25 23:10

Jeff Justice



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!