当前位置:网站首页>使用Mongoose populate实现多表关联存储与查询,内附完整代码
使用Mongoose populate实现多表关联存储与查询,内附完整代码
2022-08-08 23:03:00 【@魏大大】

文章目录
使用Mongoose populate实现多表关联与查询
mongodb不是传统的关系型数据库,我们可以使用monogoose方便的将多个表关联起来,实现一对多、多对多的数据表存储和查询功能。
本文已最常见的一对多关系模型,介绍简单的数据模型定义、存储、查询。
一、 数据模型创建
我们创建一个Person模型和一个Story模型,其中一个Person对应多个Story,也就是典型的一对多关系。
1. 创建一个PersonSchema
创建PersonSchema时,不需要为其指定_id属性,因为数据库会自动为其添加主键属性。
由于一个Person对象可以拥有多个Story对象,所以需要添加一个stories数组属性,存储与其关联的Story。
具体代码如下:
const PersonSchema = new Schema({
// _id: Schema.Types.ObjectId,
name: String,
age: Number,
stories: [{
type: Schema.Types.ObjectId, ref: 'Story' }]
})
问题解答
其中的Schema.Types.ObjectId是一种内置的特殊类型,专门用来表示对象的ID
官方解读:An ObjectId is a special type typically used for unique identifiers.
2. 创建一个StorySchema
每个Story都有一个唯一的author,也就是一个Person对象。和普通的属性不同的是,我们需要指定引用属性的类型和引用的模型名称。同样的,每个Story对象还可以拥有多个fans,同样是Person对象。这里实际上有一个循环的引用。
如果学习过关系型数据库的同学,可能对这里非常容易了解。
const StorySchema = new Schema({
author: {
type: Schema.Types.ObjectId, ref: 'Person' },
title: String,
fans: [{
type: Schema.Types.ObjectId, ref: 'Person' }]
})
3. 使用Schema创建对应的model
创建模型需要使用mongoose.model方法,该方法可以接收三个参数,其中:
- 第一个参数指模型的名称
- 第二个参数指使用的Schema
- 第三个参数指对应的mongodb数据表(集合)
以下代码分别使用StorySchema和PersonSchema创建了一个Story模型和一个Person模型
const Story = mongoose.model('Story', StorySchema, 'tb_story')
const Person = mongoose.model('Person', PersonSchema, 'tb_person')
二、数据存储
使用mongoose可以非常简单的使用面向对象的方式完成数据的存取。
1. 创建模型实例
创建一个名为xiaoming的Person对象,然后再创建一个Story,并使其引用Person._id属性。
let p1 = new Person({
name: 'xiaoming',
age: 12
})
let s1 = new Story({
title: 'The life of snow white and the dwarfs',
author: p1._id
})
s1.fans.push(p1.id)
问题解读
这里有一个不符合常理的地方,就是我在这里把故事的作者设为了故事的粉丝~~
2. 存储模型数据
使用模型的.save()方法存储对象的数据到数据库中。
p1.save().then(person => {
console.log('Pserson save success.\n', person)
s1.save().then(story => {
console.log('Story save success.\n', story)
})
})
代码指向结果如下:
Pserson save success.
{
name: 'xiaoming',
age: 12,
stories: [],
_id: new ObjectId("62ef6fb11c8795f4e1327adb"), //注意,这里对应了下面的Story.author
__v: 0
}
Story save success.
{
author: new ObjectId("62ef6fb11c8795f4e1327adb"), //注意,这里对应了上面的Person._id
title: 'The life of snow white and the dwarfs',
fans: [ new ObjectId("62ef6fb11c8795f4e1327adb") ],
_id: new ObjectId("62ef6fb11c8795f4e1327adc"),
__v: 0
}
这样数据存储工作就完成了。
三、数据关联查询
- 使用故事的标题,查询故事作者的名称
Story.findOne({
title: 'The life of snow white and the dwarfs' })
.populate('author').then(story => {
console.log(story.author.name)
})
执行结果会输出:xiaoming
2. 使用故事标题,查询粉丝信息
Story.findOne({
title: 'The life of snow white and the dwarfs' })
.populate('fans').then(story => {
console.log(story.fans)
})
代码执行结果:
[
{
name: 'xiaoming',
age: 12,
stories: [],
_id: new ObjectId("62ef781a8123a8ec47f40736"),
__v: 0
}
]
四、完整代码
const mongoose = require('mongoose')
const Schema = mongoose.Schema
mongoose.connect('mongodb://ahohAdmin:[email protected]:27017/db_ahoh')
.then('database connected')
.catch(err => console.log(err))
const PersonSchema = new Schema({
// _id: Schema.Types.ObjectId,
name: String,
age: Number,
stories: [{
type: Schema.Types.ObjectId, ref: 'Story' }]
})
const StorySchema = new Schema({
author: {
type: Schema.Types.ObjectId, ref: 'Person' },
title: String,
fans: [{
type: Schema.Types.ObjectId, ref: 'Person' }]
})
const Story = mongoose.model('Story', StorySchema, 'tb_story')
const Person = mongoose.model('Person', PersonSchema, 'tb_person')
let p1 = new Person({
name: 'xiaoming',
age: 12
})
let s1 = new Story({
title: 'The life of snow white and the dwarfs',
author: p1._id
})
s1.fans.push(p1.id)
p1.save().then(person => {
console.log('Pserson save success.\n', person)
s1.save().then(story => {
console.log('Story save success.\n', story)
})
})
Story.findOne({
title: 'The life of snow white and the dwarfs' })
.populate('author').then(story => {
console.log(story.author.name)
})
Story.findOne({
title: 'The life of snow white and the dwarfs' }).populate('fans').then(story => {
console.log(story.fans)
})
边栏推荐
- The second side of Tencent technical support internship - Tencent's father's luck is so sudden (offer received)
- CTFSHOW_WEB入门web213
- Virtualization type (with picture)
- ArcPy set the unique identification code
- IMConversation 或 IMUser 类型数据
- Unity 双生ScrollView滑动冲突问题
- iptables firewall content full solution
- Mysql数据库身份证统计sql数据库加密等操作
- Button Wizard Delete File Command
- 支付宝 To 理财排行名称修改
猜你喜欢
随机推荐
你需要来自XXX的权限才能对此文件夹进行更改
wps表格分两页断开怎么办?wps表格分两页断开的解决方法
【PP-YOLOv2】训练自定义的数据集
待完善:tf.name_scope() 和 tf.variable_scope()的区别
Excuse me: is it safe to pay treasure to buy fund on
MPLS Virtual Private Network Everywhere in Life
【Verilog基础】PPA优化问题总结(含面积优化、速度优化)
C2758105-Flash 驱动配置参考
让IPv6强大的关键——NDP邻居发现协议
C# 开发中遇到的一些小技巧
Application Layer Protocol - RADIUS
wsgw登录抓包记录
Unity ScrollView无限循环左右滑动翻页带阻尼效果
请问:支付宝上买基金安全吗
C语言 库函数汇总2019.10.31
嵌入式驱动开发整体调试
Python object-oriented
Kubernetes 资源编排系列之二: Helm 篇
ZCANPRO 通道配置方法
ABP中的数据过滤器









