当前位置:网站首页>Use Mongoose populate to implement multi-table associative storage and query, with complete code included
Use Mongoose populate to implement multi-table associative storage and query, with complete code included
2022-08-08 23:10:00 【@weida】

文章目录
使用Mongoose populateImplement multi-table association and query
mongodb不是传统的关系型数据库,我们可以使用monogooseIt is convenient to associate multiple tables,实现一对多、Many-to-many data table storage and query functions.
This article has the most common one-to-many relationship model,Introduce a simple data model definition、存储、查询.
一、 数据模型创建
我们创建一个Person模型和一个Story模型,其中一个Person对应多个Story,This is a typical one-to-many relationship.
1. 创建一个PersonSchema
创建PersonSchema时,It does not need to be specified for it_id属性,Because the database automatically adds a primary key attribute to it.
由于一个PersonObjects can have more than oneStory对象,所以需要添加一个stories数组属性,store associated with itStory.
具体代码如下:
const PersonSchema = new Schema({
// _id: Schema.Types.ObjectId,
name: String,
age: Number,
stories: [{
type: Schema.Types.ObjectId, ref: 'Story' }]
})
问题解答
其中的Schema.Types.ObjectIdis a built-in special type,Specially used to represent objectsID
官方解读:An ObjectId is a special type typically used for unique identifiers.
2. 创建一个StorySchema
每个Story都有一个唯一的author,也就是一个Person对象.Unlike ordinary properties,We need to specify the type of the referenced property and the referenced model name.同样的,每个StoryObjects can also have more than onefans,同样是Person对象.There is actually a circular reference here.
Students who have studied relational databases,Probably very easy to understand here.
const StorySchema = new Schema({
author: {
type: Schema.Types.ObjectId, ref: 'Person' },
title: String,
fans: [{
type: Schema.Types.ObjectId, ref: 'Person' }]
})
3. 使用Schema创建对应的model
Need to use to create a modelmongoose.model方法,该方法可以接收三个参数,其中:
- The first parameter refers to the name of the model
- The second parameter refers to the usedSchema
- The third parameter refers to the correspondingmongodb数据表(集合)
The following codes are used respectivelyStorySchema和PersonSchema创建了一个Story模型和一个Person模型
const Story = mongoose.model('Story', StorySchema, 'tb_story')
const Person = mongoose.model('Person', PersonSchema, 'tb_person')
二、数据存储
使用mongooseData access can be done very simply in an object-oriented way.
1. 创建模型实例
创建一个名为xiaoming的Person对象,然后再创建一个Story,and make it referencePerson._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)
问题解读
There's an outlier here,That's why I made the writer of the story a fan of the story here~~
2. Store model data
使用模型的.save()The method stores the object's data in the database.
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"), //注意,This corresponds to the followingStory.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
}
This completes the data storage job.
三、数据关联查询
- Use the title of the story,Look up the name of the author of the story
Story.findOne({
title: 'The life of snow white and the dwarfs' })
.populate('author').then(story => {
console.log(story.author.name)
})
执行结果会输出:xiaoming
2. Use a story title,Inquire about fan information
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)
})
边栏推荐
- 【CUDA】version switch freely
- wps a3格式怎么转换成a4?wps a3格式转换成a4的方法
- wps a列不见了怎么办?wps a列不见了的解决方法
- iptables firewall content full solution
- JSDay1-合并两个有序数组
- 如何搭建一套自己公司的知识共享平台
- DHCP's defense mechanism - DHCP Snooping (DHCP snooping)
- 2022牛客多校六 J-Number Game(简单推理)
- 机器学习之知识点(一)
- (2022杭电多校四)1001-Link with Bracket Sequence II(区间动态规划)
猜你喜欢

2022杭电多校五 C - Slipper (dijkstra+虚拟结点)

A preliminary study on the use of ndk and JNI

(2022牛客多校五)G-KFC Crazy Thursday(二分+哈希/Manacher)

【PP-YOLOv2】训练自定义的数据集

生活中无处不在的MPLS虚拟专用网

wps表格下拉选项怎么添加?wps表格下拉选项的添加方法

(2022杭电多校六)1010-Planar graph(最小生成树)

2022杭电多校六 1009-Map (巴那赫不动点)

【YOLOv5】6.0环境搭建(不定时更新)

最详树莓派4B装机流程及ifconfig不到wlan0的解决办法
随机推荐
JS中的原型与原型链
4399 it operations intern interview experience
【Verilog基础】关于芯片中信号串扰的理解
wps备份与恢复在哪里?
如何实现call、apply、bind
Python object-oriented
2022杭电多校五 C - Slipper (dijkstra+虚拟结点)
WeChat small program "decompiled" combat "behind to unpack the eggs
-Wl,--start-group ... -Wl,--end-group for resolving circular dependencies of several libraries
【Tensorflow2】tensorflow1.x-tensorflow2.x一些接口的转变
(2022牛客多校五)G-KFC Crazy Thursday(二分+哈希/Manacher)
postman request+加密解密
微信小程序错误 undefined Expecting ‘STRING‘,‘NUMBER‘,‘NULL‘,‘TRUE‘,‘FALSE‘,‘{‘,‘[‘, got ]解决方案
【Bug解决】ValueError: Object arrays cannot be loaded when allow_pickle=False
2022牛客多校六 A-Array(构造+哈夫曼)
2022牛客多校六 M-Z-Game on grid(动态规划)
如何搭建一套自己公司的知识共享平台
最详树莓派4B装机流程及ifconfig不到wlan0的解决办法
从洞察到决策,一文解读标签画像体系建设方法论丨DTVision分析洞察篇
(2022牛客多校五)H-Cutting Papers(签到)