Node learning record: mongodb


Node learning record: mongodb

brief introduction

TalkingMongoDBBefore data insertion, let’s briefly understand its data logical structure.
The logical structure of mongodb is a hierarchical structure, which is mainly composed of: document, collectionDatabaseThese three parts are composed of.

  • Document: composed of key / value pairs, like{a:1}{s:"abc"}It is the core unit of mongodb, the document of mongodb, which is equivalent to a row of records in a relational database.
  • Collection: multiple documents form a collection, which is equivalent to a table of a relational database.
  • Database: multiple collections, logically organized together, are databases.

One mongodb instance supports multiple databases.

Node learning record: mongodb

express setup

Install mongodb

Install mongodb on Ubuntu 16.04 for referenceMongoDB Docs

$ sudo apt-key adv --keyserver hkp:// --recv 0C49F3730359A14518585931BC711F9BA15703C6
$ echo "deb [ arch=amd64,arm64 ] xenial/mongodb-org/3.4 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.4.list
$ sudo apt-get update
$ sudo apt-get install -y mongodb-org

To install mongodb on CentOS 7, refer toMongoDB Docs

$ sudo vi /etc/yum.repos.d/mongodb-org-3.4.repo
name=MongoDB Repository
$ sudo yum install -y mongodb-org

Tool module

Mongoose can model mongodb

Installation and reference


npm install mongoose

Reference Mongoose

 var mongoose = require(“mongoose”);

Using mongoose to link databases

var db = mongoose(“mongodb://user:[email protected]:port/database”);


var mongoose = require(“mongoose”); 
var db = mongoose.connect(“mongodb://”); 
db.connection.on(“error”, function (error) { 
console. Log ("database connection failure:" + error); 
db.connection.on(“open”, function () { 
console. Log ("-- database connection succeeded! --"); 

Schema schema definition

In the pattern, we define fields and define the types of fields

var mongoose = require('mongoose')

var MovieSchema = new mongoose.Schema({
  title: String,
  language: String,
  country: String,
  year: Number,
  summary: String

Model – compile model

We call mongoose Model compiles the incoming schema, that is, the schema, and then generates a constructor

var mongoose = require('mongoose')
var MovieSchema = require('../shemas/movie')

var Movie = mongoose.model(

module.export = Movie

Documents – Document instantiation

After having the data model, to instantiate the document, you only need to call the model, that is, the constructor, and then pass in a piece of data Then call the save method. Jiu can store this data in the database

var Movie = require('./models/movie')

var movie = new Movie(){
 Title: 'mechanical warfare police',
 Doctor: 'Jose Patilia ',
 year: 2018
} (err) {
  if (err) return handleError(err)

Query of database

The query of database can be divided into batch, single or specific condition

Batch query of database:

Just call the find method of the model

var Movie = require('./models/movie')

app.get('/', function(req, res) {
   .exec(function(err, movies) {
     res.render('index', {
       title: 'jx_ Movie home page ',
       movies: movies

Database single query

var Movie = require('./models/movie')

app.get('/', function(req, res) {
   .findOne({_id: id})
   .exec(function(err, movies) {
     res.render('index', {
       title: 'jx_ Movie home page ',
       movies: movies

Database single deletion

var Movie = require(‘./models/movie’)

app.get('/', function(req, res) {
   .remove({_id: id}, function (err, movie) {
     if(err) {

Mongodb Foundation

  • Schema: a database model skeleton stored in the form of file, which does not have the operation ability of database
  • ModelModel generated by schema publishing, database operation with abstract properties and behaviors:
  • Entity: for the entity created by model, its operation will also affect the database

Explain in detail

Schema——A database model skeleton stored in the form of file can not directly lead to the database side, that is, it does not have the ability to operate the database. It is only a manifestation of the database model in the program segment. It can be said to be a data attribute model (table structure in the traditional sense) or a “set” model skeleton.

var mongoose = require("mongoose")
var TestSchema = new mongoose.Schema({
    name : {type:String},
    age : {type:Number,default:0},
    time : {type:Date,},
    emial : {type:String,default:''}
 //Basic attribute types include: string, date, numeric, Boolean, null, array, embedded document, etc

Model——In addition to the database skeleton defined in schema, the model constructed by schema also has the behavior of database operation, which is similar to the class managing database properties and behavior.

var db = mongoose.connect("mongodb://");
//Create model through schema
var TestModel = db.model("test1", TestSchema);

Entity——The entity created by model uses the save method to save data. Both model and entity can affect the operation of the database, but model is more operable than entity.

var TestEntity = new TestModel({
    name : "Lenka",
    age : 36,
    email : "[email protected]"
console.log(; // Lenka
console.log(TestEntity.age); // 36


Node. JS connect mongodb

$ cnpm install mongodb

Unlike mysql, mongodb will automatically create databases and collections, so we don’t need to create them manually before use.

insert data

Node learning record: mongodb

Node learning record: mongodbNode learning record: mongodb

Here ishttps://mlab.comBuild a mongodb database, we can see

{item: 'buy flowers'}

The data has been written in
The specific implementation can be seen in this small project written in node + Express + mongodb + EJStodo_app
Install mongodb on Windows platform

Redis installation


egg-mongooseegg. JS to operate mogodb. Let’s take this as an example to see how it works:
Node learning record: mongodb
Node learning record: mongodb
In real projects:


Node learning record: mongodb


Node learning record: mongodb


Node learning record: mongodb

reference resources

Use of mongoose in mongodb learning notes
Getting started with mongodb
Intro to NoSQL / MongoDB

Some operation commands of Mongoose

Recommended Today

The newly released hub tool of docker can directly view the account quota

Docker Desktop v3. 0 was officially released two weeks ago. From this version, docker officially promises that each update will be provided in the form of incremental update, so as to reduce the volume of download packages and improve efficiency. In addition to updating docker engine to V20 In addition to 10.0, other dependencies have […]