mongoose - the Nodejs framework of object-oriented operation mongodb

Keywords: Javascript Mongoose MongoDB Database Blockchain

introduce

Whether mysql or mongodb, the traditional way to interact with database is to write code according to the API they provide. The APIs they provide are often not easy to understand and hard to remember. If you pass wrong parameters and write a wrong symbol, you need to check the document.

The ORM (Object Relational Mapping) framework allows us to operate object-oriented without memorizing any database API. We only need to operate the object, and call the database API from the bottom of the framework, which greatly improves the development efficiency of programmers.

However, since there is one more layer of encapsulation, we must lose a little bit of performance, which can be ignored.

In NodeJS, the best ORM framework for mongodb operation is mongoose.

Install mongoose

npm install mongoose --save

If you do not have the nodejs driver installed on your machine, the nodejs driver will be installed automatically, because mongoose relies on the nodejs driver.

Document reference: Official documents of mongoose: http://mongoosejs.com/docs/index.html

Connect to database

'use strict'
let User = require('./model/user');
let mongoose = require('mongoose');
mongoose.connect("mongodb://127.0.0.1/test");

let db = mongoose.connection;
//Listening for wrong events
db.on('error', err => {
    console.log(err);
});

db.once('open', () => {
    console.log('mongodb connect successfully!');
    highOrderQuery()
});

Model definition

mongoose uses schema to describe data format, fields and rules. With schema, model can be generated to operate data.

Generally, we create a new model directory to store these model files. For example, here we create a new model/user.js

'use strict'
let mongoose = require('mongoose');
let schema = mongoose.Schema({
    nameString,
    ageNumber,
    addressString,
    fav: [String]
}, {
    versionKeyfalse
}
);

module.exports = mongoose.model("users", schema);

Additions and deletions

Directly view the Model related API in the document.

async function testCRUD({
    //increase
    let arr = [
        {
            name"Jet Li"age50address"Beijing"fav: ["Kungfu Online""perform in a film""Travel?"]
        },
        {
            name"Wu Jing"age48address"Beijing"fav: ["Kungfu Online""TV play""motion"]
        },
    ];
    let res = await User.create(arr);
    console.log(res);

    //check
    let res = await User.findOne({address"Beijing"}); //Find the first qualified document
    console.log(res);
    let res = await User.find({address"Beijing"}); //Find all documents that meet the conditions
    console.log(res);

    //change
    let res = await User.updateOne({_id"5b4065e548651d0b7035843d"}, {age11address"Shenzhen"});
    console.log(res);

    //Delete
    let res = await User.deleteOne({_id"5b4065e548651d0b7035843d"});
    console.log(res);
}

Advanced query

All conditional operators: https://docs.mongodb.com/manual/reference/operator/query/.

async function highOrderQuery({
    //Conditional query
    let res = await User.find({age: {$gt15}});

    //Array query
    let res = await User.find({
        fav"Play a game"
    });

    //Paging query
    //sort({age:1}): 1 (default) is from small to large, - 1 is from large to small
    //sort("-age"): can directly write ` - ', indicating from large to small
    //select("") selects only one or several fields; select("-fav") does not select a field
    let res = await User.find().skip(0).limit(2).sort("-age").select("-fav"); 

    console.log(res);
}

Reference resources

  • 120 day open source tutorial of blockchain development for black horse programmers

    https://github.com/itheima1/BlockChain

A fog language: operate the best NodeJS framework of mongodb.

Free knowledge Planet: A bit of customer accumulation exchange
The official account of WeChat: A code passenger
WeChat: Efon-fighting
Website: http://www.efonmark.com

Posted by jollyjumper on Sat, 07 Mar 2020 08:35:50 -0800