最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Mongo findOne inside of Array - Stack Overflow

programmeradmin3浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 6

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" 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}
})
发布评论

评论列表(0)

  1. 暂无评论