Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use mongoose to implement Multi-set Association query

2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces how to use mongoose to achieve multi-set association query, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.

When using node to develop back-end projects, you usually choose mongodb as the database, while mongodb usually chooses mongoose as the driver for operating mongodb.

First of all, we know that mongodb is a non-relational database, that is to say, the fields of each row of data saved can be different and different. Let's take the data of a simple blog system as an example, the data information involved may include users, articles, and messages.

Xiaoming posted an article, so Xiaoming's data are as follows:

{name:' Xiaoming', articles: [{content:' this is an article'}]}

Two articles:

{name:' Xiaoming', articles: [{content:' this is the content of an article'}, {content:' this is the content of the second article'}]}

And every article may have a message, such as Xiao Hong's message to Xiao Ming, then the data will be as follows:

{name:' Xiaoming', articles: [{content:' this is the content of an article', msgs: [{name:' Xiao Hong' Content:' Xiao Hong's message to Xiaoming'}]}, {content:' this is the content of the second article' Msgs: [{name:' Xiao Hong' Content:' Xiao Hong's message to Xiaoming's second article'}]}]}

Xiao Wang also left a message for Xiaoming's article, so the data are as follows:

{name:' Xiaoming', articles: [{content:' this is the content of an article', msgs: [{name:' Xiao Hong' Content:' Xiao Hong's message to Xiao Ming'}, {name:' Xiao Wang', content:' Xiao Wang's message to Xiao Ming! }]}, {content:' this is the content of the second article', msgs: [{name:' Xiao Hong' Content:' Xiao Hong's message to Xiao Ming's second article'}, {name:' Xiao Wang' Comments on the second article of content:' Xiao Wang Xiaoming!' }]}]}

The problem is, because the article information and message information are saved under the user's information, if a user's information is modified, then you need to traverse the data of other users to make changes, such as: Xiao Hong's information has been modified. then you also need to go to Xiao Ming's article to find Xiao Hong's information to modify. Or need to modify the article also need to be modified through the user's information. This is troublesome and inefficient.

So there is a database relational query, mongodb is also most like a relational database of non-relational database, that is, let their same category data exist in the same set (table), let a field in the row do the corresponding relationship between the set and the collection, usually use id as the mapping relationship between the collection.

We use mongoose directly to manipulate mongodb:

First prepare three collections (tables)

Users stores user information

Articles stores article information, and each article belongs to a user (associated with the user field and the _ id field of users)

Msgs: store messages. Each message belongs to a user, and each message also belongs to an article. (associate the user field with the id field of users, and the article field with the id of articles)

The relationship is shown in the following figure:

The corresponding Scheme (the _ id field is automatically added when the data is saved, so we don't need to define it)

UserModel.js

Const mongoose = require ('. / db'); const schema = mongoose.Schema ({username:String, password: String}, {collection:'users'}) const model = mongoose.model ('users',schema) module.exports = model

ArticleModel.js

Const mongoose = require ('. / db'); const schema = mongoose.Schema ({title: String, content: String, user: {type: mongoose.Schema.Types.ObjectId, ref:'users'}}, {collection:'articles'}) const model = mongoose.model ('articles',schema) module.exports = model

MsgModel.js

Const mongoose = require ('. / db'); const schema = mongoose.Schema ({content: String, user: {type: mongoose.Schema.Types.ObjectId, ref:'users'}, article: {type: mongoose.Schema.Types.ObjectId, ref:'articles'},}, {collection:'msgs'}) const model = mongoose.model ('msgs',schema) module.exports = model; Association query (one-to-one)

1. Query articles correspond to the user information of query articles

Populate the method using the populate method

Parameter 1: the associated field to be queried

Parameter 2: the information from the associated query needs to be displayed.

ArticleModel.find () .populate ('user','username avatar') .exec (function (err,as) {console.log (as)})

In this way, the article information is queried with user information instead of just one user id

Association query (one-to-many)

Want to check the article, and then check out all the messages about this article

1. Aggregate query method:

Here, you need to use an aggregate query, which is as follows

/ / Multi-collection association query articleModel.aggregate ([{$lookup: {from:'msgs', / / associated collection localField:'_id', / / locally associated field foreignField:'article' / / the field as:'mms', / / result field name associated with the other set,},}], (err,dds) = > {console.log (dds)})

You can use the aggregate query using the aggregate () method, which receives an array parameter

$lookup means associated query, just like join in SQL

two。 Virtual field query mode

Add the following code to articleModel.js

Schema.virtual ('mms', {/ / Parameter 1 is the added virtual field name ref:'msgs', / / the collection of the associated query localField:' _ id', / / the fields associated with the current collection and the other collection foreignField: 'article', / / whether the fields associated with the other collection and this collection count: true / / count only show the total number of entries True for display, false for do not display}) / / the following two sentences must be added, the virtual field can be seen explicitly, otherwise you can only implicitly use schema.set ('toObject', {virtuals:true}) schema.set (' toJSON', {virtuals:true})

The virtual method is to add virtual fields to schema

Parameter 1: name of the virtual field

Parameter 2: configuration of virtual fields

Then query through populate

ArticleModel.find () .populate ('mms') .exec ((err,as) = > {console.log (as)})

In this way, the list of articles queried has a mms field, which corresponds to the total number of messages for this article.

Thank you for reading this article carefully. I hope the article "how to use mongoose to achieve multi-set related queries" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 258

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report