Advanced mongoose query operations

Source: Internet
Author: User

The convenience of Mongoose operation set is indeed not general, but it is mainly because you design the set in reference, however, it is a little troublesome for Mongoose to limit and identify the combination of sets when using ref to associate a set. But it doesn't matter. It's easy to use.

1. usage of the ref associated document in mongoose

2. query related documents by populate in mongoose

3. query to obtain a single set in the array

For example, there is a set:

{"_ Id": 11111, "Im": {"usergroup": [{"name": "friend list-2", "level": 1, "_ id": "53c4820263256dc316e98727", "list": [{"_ User": {"nickname": "mengmengfeiyang-2", "_ id": 22222, "icon": "/default/heads/2.png" }}, {" _ User ": NULL },{" _ User ": NULL },{" _ User ": null },{ "_ User": NULL },{ "_ User": NULL}] },{ "_ id": "53c488bf95ad1de01756db88", "name ": "Test usergroup", "level": 1, "list": []}

The above _ User indicates the associated document. If you only want to get one of the usergroup, and the condition is {'usergroup. $ ': 1}, you can get a code that meets the conditions as follows:

 UserModel.User.findOne({_id:11111,‘im.usergroup._id‘:‘53c488bf95ad1de01756db88‘},{‘im.usergroup.$‘:1})        .populate(‘im.usergroup.list._user‘,{icon:1,nickname:1,_id:1,name:1,remark:1})        .exec(function(err, ug){            cb(err,ug);        })

The above usermodel. user is the user's Mongoose Model

After query, you can get the following information:

{    "_id": 11111,    "im": {        "usergroup": [            {                "_id": "53c488bf95ad1de01756db88",                "name": "test usergroup",                "level": 1,                "list": []            }        ]    }}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.