mongoose④


前言


一、集合关联

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
  }
]

总结

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值