Home  >  Article  >  Web Front-end  >  What are mongooes in node

What are mongooes in node

青灯夜游
青灯夜游Original
2022-03-22 17:16:342019browse

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

What are mongooes in node

The operating environment of this tutorial: windows7 system, nodejs version 12.19.0, DELL G3 computer.

Mongoose

Mongoose is a module of Nodejs. This module can operate the MongoDB module to operate the database.

Mongooose is An Object Document Model (ODM) library that further optimizes and encapsulates Node's native MongoDB module and provides more functions.

Mongoose is an object model tool for MongoDB. It is a nodejs driver for MongoDB developed based on node-mongodb-native. It is also currently the preferred library for Node.js to operate MongoDB.

Benefits of Mongoose

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

  • Objects/documents in the model can be verified

  • Data can be type-converted to the object model

  • Can be applied using middleware Business logic hooking

  • Easier than Node’s native MongoDB driver

Note: To use it, you must first install node.js and mongodb.

mongoose installation

npm install mongoose

After successful installation, as shown below:

Successful installation After that, you can use it through require('mongoose')!

Connection string

Create a db.js

var mongoose = require('mongoose'),
    DB_URL = 'mongodb://localhost:27017/mongoosesample';/**
 * 连接 */mongoose.connect(DB_URL);/**
  * 连接成功  */mongoose.connection.on('connected', function () {    
    console.log('Mongoose connection open to ' + DB_URL);  
});    

/**
 * 连接异常 */mongoose.connection.on('error',function (err) {    
    console.log('Mongoose connection error: ' + err);  
});    
 
/**
 * 连接断开 */mongoose.connection.on('disconnected', function () {    
    console.log('Mongoose connection disconnected');  
});

Call node db.js to execute and you will see the output As shown in the figure below

As can be seen 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 10 events in the connection There are several events mentioned above, the key depends on which event you want to monitor.

Other events can be viewed by yourself: http://mongoosejs.com/docs/api.html#connection_Connection

This is the simplest connection string, of course there are other forms, such as: Connection password, database connection settings, cluster mode connection, etc. are explained here. Please check the API documentation by yourself when using it

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

Schema

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

We first transform db.js and export the mongoose object

var mongoose = require('mongoose'),
    DB_URL = 'mongodb://localhost:27017/mongoosesample';/**
 * 连接 */mongoose.connect(DB_URL);/**
  * 连接成功  */mongoose.connection.on('connected', function () {    
    console.log('Mongoose connection open to ' + DB_URL);  
});    

/**
 * 连接异常 */mongoose.connection.on('error',function (err) {    
    console.log('Mongoose connection error: ' + err);  
});    
 
/**
 * 连接断开 */mongoose.connection.on('disconnected', function () {    
    console.log('Mongoose connection disconnected');  
});    

module.exports = mongoose;

Next we define a user Schema and name it 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

Schema Types built-in types are as follows:

  • String

  • Number

  • ##Boolean | Bool

  • Array

  • ##Buffer

  • Date

  • ##ObjectId | Oid

  • ##Mixed
  • ##You can also do some things in Schema Commonly used things will be discussed later!

Model

After defining the Schema, the next step is to generate the Model.

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

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

/**
 * 用户信息 */
 var mongoose = require('./db.js'),
    Schema = mongoose.Schema;var UserSchema = new Schema({          
    username : { type: String },                    //用户账号
    userpwd: {type: String},                        //密码
    userage: {type: Number},                        //年龄
    logindate : { type: Date}                       //最近登录时间
 });
 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");
/**
 * 插入 
*/
 function insert() { 
    var user = new User({
        username : 'Tracy McGrady',                 //用户账号
        userpwd: 'abcd',                            //密码
        userage: 37,                                //年龄
        logindate : new Date()                      //最近登录时间    
    });

    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

From the picture, you can see that the insertion was successful!

  更新 

  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方法基本可以满足所有更新!

  常用方法还有findByIdAndUpdate,这种比较有指定性,就是根据_id

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

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

findByIdAndUpdate();

  其它更新方法

  Model.findOneAndUpdate([conditions], [update], [options], [callback])      //找到一条记录并更新

  删除

  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();

  结果就不贴了,res中会返回是否成功以及影响的行数:{"ok":1,"n":1}

  其它常用方法还有: 

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

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

  条件查询

  已先插入一些测试数据 。。

  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();

  结果我就不展示了

  第2个参数可以设置要查询输出的字段,比如改成

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();

  输出只会有username字段,设置方法如上,1表示查询输出该字段,0表示不输出

  比如我要查询年龄范围条件应该怎么写呢?

  User.find({userage: {$gte: 21, $lte: 65}}, callback);    //这表示查询年龄大于等21而且小于等于65岁

  其实类似的还有: 

  $or    或关系

  $nor    或关系取反

  $gt    大于

  $gte    大于等于

  $lt     小于

  $lte     小于等于

  $ne            不等于

  $in             在多个值范围内

  $nin           不在多个值范围内

  $all            匹配数组中多个值

  $regex  正则,用于模糊查询

  $size   匹配数组大小

  $maxDistance  范围查询,距离(基于LBS)

  $mod     取模运算

  $near   邻域查询,查询附近的位置(基于LBS)

  $exists    字段是否存在

  $elemMatch  匹配内数组内的元素

  $within  范围查询(基于LBS)

  $box    范围查询,矩形范围(基于LBS)

  $center       范围醒询,圆形范围(基于LBS)

  $centerSphere  范围查询,球形范围(基于LBS)

  $slice    查询字段集合中的元素(比如从第几个之后,第N到第M个元素)

  可能还有一些,没什么印象,大家自行看看api ^_^!  

  数量查询

  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会输出数量,也可以传入条件做条件查询!

  根据_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();

  这个还是比较常用,要据ID得到数据!  

  模糊查询

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();

  上面示例中查询出所有用户名中有'm'的名字,且不区分大小写,模糊查询比较常用,正则形式匹配,正则方式就是javascript正则,用到的比较多!

  分页查询

var User = require("./user.js");

function getByPager(){
    
    var pageSize = 5;                   //一页多少条
    var currentPage = 1;                //当前第几页
    var sort = {'logindate':-1};        //排序(按登录时间倒序)
    var condition = {};                 //条件
    var skipnum = (currentPage - 1) * pageSize;   //跳过数
    
    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();

  分页是用得比较多的查询,分页原理用过其它数据库的都知道,分页用到的函数和mysql的比较类似

  上面我用到sort(),这个是排序规则,就不单讲了!

其它操作

  其它还有比较多常用的

  索引和默认值

  再看看我对user.js这个schema的修改

/**
 * 用户信息
 */
var mongoose = require('./db.js'),
    Schema = mongoose.Schema;

var UserSchema = new Schema({          
    username : { type: String , index: true},                    //用户账号
    userpwd: {type: String},                        //密码
    userage: {type: Number},                        //年龄
    logindate : { type: Date, default:Date.now}                       //最近登录时间
});

module.exports = mongoose.model('User',UserSchema);

  index :建索引

  default:默认值

  LBS地址位置

lbs : { type: Array, index: '2d', sparse: true }   //地理位置

  上面有介绍过很多基于LBS的条件查询,Schema中定义时如上

  LBS查询对于一些基于LBS应用会用得比较多。

  其它常用方法

  Model.distinct(field, [conditions], [callback])                  //去重

  Model.findOne(conditions, [fields], [options], [callback])             //查找一条记录

  Model.findOneAndRemove(conditions, [options], [callback])           //查找一条记录并删除

  Model.findOneAndUpdate([conditions], [update], [options], [callback])      //查找一条记录并更新

更多node相关知识,请访问:nodejs 教程

The above is the detailed content of What are mongooes in node. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn