Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 views
in Technique[技术] by (71.8m points)

mongodb - How does mongoose link lists

I am a newbie and am using [email protected] in nodejs

I now have the "cats" table:

{ name: String, breed: ObjectId }

and the "breeds" table:

{ breed: String }

When I query a Cat with "5ff67de6fc4440317469ef1d", I want to return

{
  _id: "5ff67de6fc4440317469ef1d",
  name: 'cat 1',
  breed: {
    _id: "5ff67afda6c7062a2a97575e"
    breed: 'breed 1'
  }
}

But how do I define "Schema", how do I query it, please help me, thanks


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

use populate:

this.catModel.find().populate('breed');

// result
[
    {
        "name": "aaa", 
        "breed": {
            "breed": "type 2", 
            "_id": "5ff67afda6c7062a2a97575f"
        }, 
        "_id": "5ff67de6fc4440317469ef1d"
    }
]

use lookup:

this.catModel
.aggregate()
.lookup({
  from: 'breeds',
  localField: 'breed',
  foreignField: '_id',
  as: 'breed',
  })
.project({ __v: 0 });

// result
[
    {
        "_id": "5ff67de6fc4440317469ef1d", 
        "name": "aaa", 
        "breed": [
            {
                "_id": "5ff67afda6c7062a2a97575f", 
                "breed": "type 2"
            }
        ]
    }
]

document


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...