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 the concept of mongooes in node

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly introduces "what is the concept of mongooes in node". In daily operation, I believe that many people have doubts about the concept of mongooes in node. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubts of "what is the concept of mongooes in node?" Next, please follow the editor to study!

In node, mongooes is a third-party module and an object document model (ODM) library. It further optimizes and encapsulates the native MongoDB module of Node. It can operate the MongoDB database by manipulating the object model.

This tutorial operating environment: windows7 system, nodejs version 12.19.0, DELL G3 computer.

Mongoose

Mongoose is a module of Nodejs, which can operate the MongoDB module on the database.

Mongooose is an object document Model (ODM) library that further optimizes the encapsulation of Node's native MongoDB module and provides more functionality.

Mongoose, an object model tool of MongoDB, is a nodejs driver of MongoDB based on node-mongodb-native, and is currently the preferred library for Node.js operation MongoDB.

Benefits of Mongoose

You can create a schema structure (constraint) (Schema) for the document

Objects / documents in the model can be validated

Data can be converted to an object model by type

You can use middleware to apply business logic hooks

Easier than Node's native MongoDB driver

Note: to use it, you have to install node.js and mongodb first.

Mongoose installation

Npm install mongoose

After successful installation, the figure is as follows:

After the installation is successful, you can use it through require ('mongoose')!

Connection string

Create a db.js

Var mongoose = require ('mongoose'), DB_URL =' mongodb://localhost:27017/mongoosesample';/** * connection * / mongoose.connect (DB_URL); / * * connection succeeded * / mongoose.connection.on ('connected', function () {console.log (' Mongoose connection open to'+ DB_URL);}) / * * connection exception * / mongoose.connection.on ('error',function (err) {console.log (' Mongoose connection error:'+ err);}); / * * connection disconnection * / mongoose.connection.on ('disconnected', function () {console.log (' Mongoose connection disconnected');})

When you call node db.js to execute, you will see the following output

As you can see from the code, several events are monitored and the execution triggers the connected event, which indicates that the connection is successful

There are more than just a few events in connection, it depends on which event you want to listen to.

Other events can be viewed on your own: http://mongoosejs.com/docs/api.html#connection_Connection

This is the simplest connection string, and of course there are other forms, such as connection password, database connection settings, cluster connection, and so on. It is explained here that when you use it, you can query the API document yourself.

Http://mongoosejs.com/docs/api.html#index-js

Schema

Schema is a data schema used in mongoose, which can be understood as the definition of table structure; each schema is mapped to a collection in mongodb, which does not have the ability to manipulate the database.

Let's first modify db.js and export mongoose objects.

Var mongoose = require ('mongoose'), DB_URL =' mongodb://localhost:27017/mongoosesample';/** * connection * / mongoose.connect (DB_URL); / * * connection succeeded * / mongoose.connection.on ('connected', function () {console.log (' Mongoose connection open to'+ DB_URL);}) / * * connection anomaly * / mongoose.connection.on ('error',function (err) {console.log (' Mongoose connection error:'+ err);}); / * * connection disconnection * / mongoose.connection.on ('disconnected', function () {console.log (' Mongoose connection disconnected');}); module.exports = mongoose

Let's define a Schema for user, named user.js

Mongoose = require ('. / db.js'= UserSchema = userpwd: {type: String}, userage: {type: Number}, logindate: {type: Date}

Defining a Schema is as simple as specifying the field name and type

The built-in types of Schema Types are as follows:

String

Number

Boolean | Bool

Array

Buffer

Date

ObjectId | Oid

Mixed

There are some common things you can do in Schema, which we'll talk about later!

Model

Once the Schema is defined, the next step is to generate the Model.

Model is a model generated by schema, which can operate on the database.

We generate a User model for the schema of user defined above and export it. The modified code is as follows

/ * * user information * / var mongoose = require ('. / db.js'), Schema = mongoose.Schema Var UserSchema = new Schema ({username: {type: String}, / / user account userpwd: {type: String}, / / password userage: {type: Number}, / / Age logindate: {type: Date} / / Last login time}) Module.exports = mongoose.model ('User',UserSchema); common database operations

Next, create a test.js file to demonstrate some common operations.

insert

Model#save ([fn])

Var User = require (". / user.js") / * insert * / function insert () {var user = new User ({username: 'Tracy McGrady', / / user account userpwd:' abcd', / / password userage: 37 / / Age logindate: new Date () / / Last logon time}) User.save (function (err, res) {if (err) {console.log ("Error:" + err);} else {console.log ("Res:" + res);}});} insert ()

The results are viewed in the robmongo tool

You can see from the picture that the insertion was successful!

Update

Model.update (conditions, update, [options], [callback])

Var User = require (". / user.js"); function update () {var wherestr = {'username':' Tracy McGrady'}; var updatestr = {'userpwd':' zzzz'}; User.update (wherestr, updatestr, function (err, res) {if (err) {console.log ("Error:" + err);} else {console.log ("Res:" + res) }})} update ()

Update the password according to the user name, and the result is as shown in the figure.

As can be seen in the picture, the password was updated successfully! The update method can basically satisfy all updates!

The common method is findByIdAndUpdate, which is specified according to _ id.

Model.findByIdAndUpdate (id, [update], [options], [callback])

Var User = require (". / user.js"); function findByIdAndUpdate () {var id = '56f2558b2dd74855a345edb2Qing; var updatestr = {' userpwd': 'abcd'}; User.findByIdAndUpdate (id, updatestr, function (err, res) {if (err) {console.log ("Error:" + err);} else {console.log ("Res:" + res) }})} findByIdAndUpdate ()

Other update methods

Model.findOneAndUpdate ([conditions], [update], [options], [callback]) / / find a record and update

Delete

Model.remove (conditions, [callback])

Var User = require (". / user.js"); function del () {var wherestr = {'username':' Tracy McGrady'}; User.remove (wherestr, function (err, res) {if (err) {console.log ("Error:" + err);} else {console.log ("Res:" + res);}})} del ()

As a result, it will not be posted. The res will return the number of rows that are successful and affected: {"ok": 1, "n": 1}

Other common methods include:

Model.findByIdAndRemove (id, [options], [callback])

Model.findOneAndRemove (conditions, [options], [callback])

Conditional query

Some test data has been inserted first.

Model.find (conditions, [fields], [options], [callback])

Var User = require (". / user.js"); function getByConditions () {var wherestr = {'username':' Tracy McGrady'}; User.find (wherestr, function (err, res) {if (err) {console.log ("Error:" + err);} else {console.log ("Res:" + res);}})} getByConditions ()

As a result, I won't show it.

The second parameter can set the field to query the output, such as changing to

Var User = require (". / user.js"); function getByConditions () {var wherestr = {'username':' Tracy McGrady'}; var opt = {"username": 1, "_ id": 0}; User.find (wherestr, opt, function (err, res) {if (err) {console.log ("Error:" + err) } else {console.log ("Res:" + res);}})} getByConditions ()

The output will only have a username field. The setting method is as above. 1 means the query outputs the field, and 0 means no output.

For example, if I want to inquire about the age range, how should I write it?

User.find ({userage: {$gte: 21, $lte: 65}}, callback); / / this means that the query age is greater than 21 and less than or equal to 65.

In fact, there are similar ones:

$or or relationship

$nor or relationship inversion

$gt is greater than

$gte greater than or equal to

$lt is less than

$lte less than or equal to

$ne is not equal to

$in is in multiple value range

$nin is not in the range of multiple values

$all matches multiple values in the array

$regex regular for fuzzy queries

$size matches the array size

$maxDistance range query, distance (based on LBS)

$mod modular operation

$near neighborhood query to query nearby locations (based on LBS)

Whether the $exists field exists

$elemMatch matches elements in the inner array

$within range query (based on LBS)

$box range query, rectangular range (based on LBS)

$center range alert, circular range (based on LBS)

$centerSphere range query, spherical range (based on LBS)

$slice queries the elements in the field collection (for example, after which, the Nth to the Mth)

There may be some, but I don't have much impression. Take a look at api ^ _ ^!

Quantity query

Model.count (conditions, [callback])

Var User = require (". / user.js"); function getCountByConditions () {var wherestr = {}; User.count (wherestr, function (err, res) {if (err) {console.log ("Error:" + err);} else {console.log ("Res:" + res);}} getCountByConditions ()

Res will output the quantity, you can also pass in the condition to do conditional query!

Query according to _ id

Model.findById (id, [fields], [options], [callback])

Var User = require (". / user.js"); function getById () {var id = '56f261fb448779caa359cb73); User.findById (id, function (err, res) {if (err) {console.log ("Error:" + err);} else {console.log ("Res:" + res);}} getById ()

This is still quite commonly used, according to the ID to get the data!

Fuzzy query

Var User = require (". / user.js"); function getByRegex () {var whereStr = {'username': {$regex:/m/i}}; User.find (whereStr, function (err, res) {if (err) {console.log ("Error:" + err);} else {console.log ("Res:" + res);}})} getByRegex ()

In the above example, there are'm 'names in all user names, and they are not case-sensitive, fuzzy queries are more commonly used, regular forms match, regular ways are javascript regular, and more are used!

Paging query

Var User = require (". / user.js"); function getByPager () {var pageSize = 5; / / how many entries per page var currentPage = 1; / / current page var sort = {'logindate':-1}; / / sort (in reverse order of login time) var condition = {} / / conditional var skipnum = (currentPage-1) * pageSize; / / skips User.find (condition) .skip (skipnum) .limit (pageSize) .sort (sort) .exec (function (err, res) {if (err) {console.log ("Error:" + err);} else {console.log ("Res:" + res) }})} getByPager ()

Paging is a frequently used query. Anyone who has used the paging principle in other databases knows that the functions used in paging are similar to those in mysql.

Above I use sort (), this is the collation, not just talk about!

Other operations

There are more commonly used ones.

Index and default value

Let's take a look at my changes to the schema of user.js.

/ * * user information * / var mongoose = require ('. / db.js'), Schema = mongoose.Schema Var UserSchema = new Schema ({username: {type: String, index: true}, / / user account userpwd: {type: String}, / / password userage: {type: Number}, / / Age logindate: {type: Date Default:Date.now} / / Last logon time}) Module.exports = mongoose.model ('User',UserSchema)

Index: indexing

Default: default

LBS address location

Lbs: {type: Array, index: '2dwells, sparse: true} / / Geographic location

Many LBS-based conditional queries have been introduced above, as defined in Schema

LBS queries are often used for some LBS-based applications.

Other common methods

Model.distinct (field, [conditions], [callback]) / / weight removal

Model.findOne (conditions, [fields], [options], [callback]) / / find a record

Model.findOneAndRemove (conditions, [options], [callback]) / / find a record and delete

Model.findOneAndUpdate ([conditions], [update], [options], [callback]) / / find a record and update

At this point, the study of "what is the concept of mongooes in node" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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

Development

Wechat

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

12
Report