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

What is Mongoose in egg? How do I use it?

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

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

This article will explain in detail what Mongoose is in egg. How do I use it? The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

What is Mongoose?

Mongoose is an object model tool of MongoDB, which encapsulates many common methods such as adding, deleting, modifying and querying documents by MongoDB, which makes it more flexible and simple for NodeJS to operate Mongodb database.

How to use it in egg projects?

1. Installation

Npm I egg-mongoose-- save

2. Configuration

Configure the plug-in in / config/plugin.js under the root directory

Exports.mongoose = {enable: true, package: 'egg-mongoose',}

3. Connect to the database

Add configuration to / config/config.default.js under the root directory, where url is our database address, you can distinguish between the development environment and the production environment by environment variables, and determine whether to use the database of username and password

Const prod = process.env.npm_config_server_prod

Mongoose: {client: {url: prod? 'mongodb:eggadmin:123456@localhost:27017/DbName':' mongodb://127.0.0.1:27017/DbName', options: {useUnifiedTopology: true,}

4. Configuration and use

(1) Datasheet configuration

Create a new model folder under the app directory, and create a new JS file under the model folder as the configuration content of the data table. Take the configuration of the book table as an example.

'use strict';/** * @ description: Mongoose book Schema, * / module.exports = app = > {const mongoose = app.mongoose; const Schema = mongoose.Schema Const BookSchema = new Schema ({desc: {type: String}, / * Book description * / name: {type: String}, / * Book title * / press: {type: String}, / * Press * / author: {type: String}, / * author * / image: {type: Array}, / * Book Picture list * / price: {type: String} / * Price * / book_type: {/ * Book category id * / type: Schema.Types.ObjectId, ref: 'BookClassify',}, user: {/ * Book publisher id * / type: Schema.Types.ObjectId, ref:' User',}, create_time: {type: String}, / * creation time * / status: {type: String}, / * status 1: to be purchased, 2: purchased * / look: {type: Number} / * number of views * /}) Return mongoose.model ('Book', BookSchema);}

You can see that we can define the table structure through Schema, specify the type and association of fields, and generate model after setting the field. This is a very simple configuration. For more configuration methods, please see the documentation.

(2) use mongoose method

After configuring the data table structure, we can call the mongoose method in the service layer to add, delete, query and modify the document. The processing logic of the list of books is taken as an example.

Async findbookList (data) {const {type, page, pageSize, desc, status, userId} = data; const searchVal = {} if (type) {searchVal.book_type = mongoose.Types.ObjectId (type)} if (status) {searchVal.status = status} if (userId) {searchVal.user = mongoose.Types.ObjectId (userId)} const search_term = {$or: [{desc: {$regex: desc? Desc:'', $options:'$i'}}, {name: {$regex: desc? Desc:'', $options:'$i'}}, {author: {$regex: desc? Desc:'', $options:'$i'}}, {press: {$regex: desc? Desc:', $options:'$i'}},],}; const totalNum = await this.ctx.model.Book.find (searchVal) .and (search_term) .countDocuments () Const result = await this.ctx.model.Book.find (searchVal) .populate ({path: 'user', select: {name: 1, image: 1}}) .populate ({path:' book_type'}) .and (search_term) .sort ({create_time:-1}) .skip ((parseInt (page)-1) * parseInt (pageSize)) .limit (parseInt (pageSize)) Return result? {bean: {records: result, current: page, size: result.length, total: totalNum,},... app.config.msg.GET_SUCCESS}: app.config.msg.GET_ERR;}

As you can see, the model of Book can be obtained through this.ctx.model.Book and the methods needed by mongoose can be called, such as populate, find, and, sort, skip, limit, and so on.

5. Common methods of egg-Mongoose

Increase data

This.ctx.model.Book.create (data,callback)

Data is the json data structure, and callback is the callback function after operation.

Query data

Gets all the data and returns an array

This.ctx.model.Book.find ()

Gets a data and returns an object

This.ctx.model.Book.findOne ()

Conditional query

This.ctx.model.Article.find (conditions,callback)

Where conditions is the condition of query and callback is the callback function.

There are several situations in conditions:

Specific data:

This.ctx.model.Book.find ({_ id:5c4a19fb87ba4002a47ac4d, name: The Legend of the Condor Heroes}, callback)

Conditional query:

"$lt" less than "$lte" less than or equal to "$gt" greater than "$gte" greater than or equal to "$ne" not equal to / query this.ctx.model.Book.find array of books with prices greater than 100 and less than 200 ({"price": {$get:100, $lte:200})

Or query OR

"$in" a key corresponds to multiple values "$nin", and a key does not correspond to the specified value "$or". Multiple conditions match. You can nest $in to use "$not" to reverse the above, and query the document this.ctx.model.Book.find that does not match a specific pattern ({"name": {$in: ["shooting carving", "relying on Heaven"]}).

Delete data

This.ctx.model.Book.remove (conditions,callback)

Update data

This.ctx.model.Book.update (conditions, update, callback)

Conditions is the condition, update is the updated value object

Sort

This.ctx.model.Book.sort ({create_time:-1})

Where-1 indicates a descending return. 1 indicates that ascending order is returned

Limit the quantity

This.ctx.model.Book.limit (number)

Number indicates the number of restrictions

Skip document return

This.ctx.model.Book.skip (number)

Number indicates the number of skips. Skip is often paged with limit.

Conditional array and

After find, you can use and to further filter the query results, which is equivalent to and.

Const search_term = {$or: [{desc: {$regex: desc? Desc:'', $options:'$i'}}, {name: {$regex: desc? Desc:'', $options:'$i'}}, {author: {$regex: desc? Desc:'', $options:'$i'}}, {press: {$regex: desc? Desc:', $options:'$i'}},],}; this.ctx.model.Book.find () .and (search_term)

Association query populate

/ / if you specify the associated table name when configuring fields in model, you can query the table association through populate: {/ * Book publisher id * / type: Schema.Types.ObjectId, ref: 'User',}, this.ctx.model.Book.find () .populate ({path:' user', select: {name: 1, image: 1}})

Aggregation pipeline Aggregate

This.ctx.model.Template.aggregate ([{$match: {name}}, {$sort: {create_time:-1}}, {$group: {_ id:'$name', user_id: {$first:'$modifier'},])

The common operations of Mongoose aggregation pipeline aggregate are $project, $match, $group, $sort, $limit, $skip, $lookup table association.

Batch operation bulkWrite

Const template_list = await ctx.model.Template.aggregate ([{$sort: {create_time:-1}}, {$group: {_ id:'$name', template_id: {$first:'$_ id'}, label: {$first:'$label'},]); const update_value = [] Template_list.forEach (item = > {if (! item.label) {update_value.push ({updateOne: {filter: {_ id: item.template_id}, update: {label:''},},});}}); await ctx.model.Template.bulkWrite (update_value)

Can carry out a series of batch add, delete, update and other operations.

There are many ways for me to use mongoose flexibly. When we use it, we can choose the right method combined with business logic to improve the efficiency of our database operation. We can read the official documents carefully before we use it.

About what Mongoose is in egg? How do I use it? So much for sharing here. I hope the above content can help you to some extent and learn more knowledge. If you think the article is good, you can share it for more people to see.

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: 0

*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

Database

Wechat

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

12
Report