网络知识 娱乐 使用Mongoose populate实现多表关联存储与查询,内附完整代码

使用Mongoose populate实现多表关联存储与查询,内附完整代码

在这里插入图片描述


文章目录

  • 使用Mongoose populate实现多表关联与查询
    • 一、 数据模型创建
      • 1. 创建一个PersonSchema
      • 2. 创建一个StorySchema
      • 3. 使用Schema创建对应的model
    • 二、数据存储
      • 1. 创建模型实例
      • 2. 存储模型数据
    • 三、数据关联查询
    • 四、完整代码

使用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方法,该方法可以接收三个参数,其中:

  1. 第一个参数指模型的名称
  2. 第二个参数指使用的Schema
  3. 第三个参数指对应的mongodb数据表(集合)
    以下代码分别使用StorySchemaPersonSchema创建了一个Story模型和一个Person模型
const Story = mongoose.model('Story', StorySchema, 'tb_story')
const Person = mongoose.model('Person', PersonSchema, 'tb_person')

二、数据存储

使用mongoose可以非常简单的使用面向对象的方式完成数据的存取。

1. 创建模型实例

创建一个名为xiaomingPerson对象,然后再创建一个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
}

这样数据存储工作就完成了。

三、数据关联查询

  1. 使用故事的标题,查询故事作者的名称
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:123456@localhost: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)
})