前言
一、集合关联
1、创建model
代码如下:
const booksSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
author: {
type: mongoose.Schema.Types.ObjectId, // ObjectId类型
ref: 'user' // 外键来自哪个集合,不需要加s
}
})
const usersSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
})
const Book = mongoose.model('book', booksSchema)
const User = mongoose.model('user', usersSchema)
集合中的文档:
2、查询文档并填充关联字段信息
方法原型:
Query.prototype.populate()
Parameters
path «Object|String» either the path to populate or an object specifying all parameters
[select] «Object|String» Field selection for the population query
[model] «Model» The model you wish to use for population. If not specified, populate will look up the model by the name in the Schema's ref field.
[match] «Object» Conditions for the population query
[options] «Object» Options for the population query (sort, etc)
[options.path=null] «String» The path to populate.
[options.retainNullValues=false] «boolean» by default, Mongoose removes null and undefined values from populated arrays. Use this option to make populate() retain null and undefined array entries.
[options.getters=false] «boolean» if true, Mongoose will call any getters defined on the localField. By default, Mongoose gets the raw value of localField. For example, you would need to set this option to true if you wanted to add a lowercase getter to your localField.
[options.clone=false] «boolean» When you do BlogPost.find().populate('author'), blog posts with the same author will share 1 copy of an author doc. Enable this option to make Mongoose clone populated docs before assigning them.
[options.match=null] «Object|Function» Add an additional filter to the populate query. Can be a filter object containing MongoDB query syntax, or a function that returns a filter object.
[options.transform=null] «Function» Function that Mongoose will call on every populated document that allows you to transform the populated document.
[options.options=null] «Object» Additional options like limit and lean.
Returns:
«Query» this
Specifies paths which should be populated with other documents.// 指定应使用其他文档填充的路径。
代码如下:
Book.find({}, (err, res) => {
console.log(res);
}).populate('author')// 关联字段
执行结果:
[
{
_id: new ObjectId("61e3b31a92933c6cf0d9d216"),
name: '凡人修仙传',
author: {
_id: new ObjectId("61e3b2f75189c61bd4381158"),
name: '忘语',
__v: 0
},
__v: 0
}
]