Node.js uses mongoose to manipulate mongodb

1. Software configuration:

1.node v8.9.3
2. npm 5.5.1
3. For the mongoose and MongoDB versions, see package.json below.

// package.json
{
  "name": "mongoosedemo",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "mongodb": "^3.1.1",
    "mongoose": "^5.2.4"
  }
}

2. Connection string

2.1 Connection String

// db.js

const mongoose = require('mongoose');
const DB_URL = 'mongodb://localhost:27017/mydatabase1';

// Connect
mongoose.connect(DB_URL, { useNewUrlParser: true });
// Successful connection
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 disconnect
mongoose.connection.on('disconnected', function () {
  console.log('Mongoose connection disconnected ');
})

// Modify the last line of db.js above to export the mongoose object
const mongoose = require('mongoose');
const DB_URL = 'mongodb://localhost:27017/mydatabase1';

// Connect
mongoose.connect(DB_URL, { useNewUrlParser: true });
// Successful connection
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 disconnect
mongoose.connection.on('disconnected', function () {
  console.log('Mongoose connection disconnected ');
})

module.exports = mongoose;

2.2 Schema

// Define a user's Schema, named user.js

/**
 * User information
 */
// Define database table storage structure
const mongoose = require('./db');
const Schema = mongoose.Schema;

const UserSchema = new Schema({
  username: { type: String }, // User name
  password: { type: String }, // User password
  age: { type: String }, // User age
  lastLoinDate: { type: Date } // Last logon time
})

2.3 Model

With Schema defined, the next step is to generate the Model.
Model is a schema-generated model that can operate on databases

// Modify the user.js above, convert Schema to Model, and export
// user.js

/**
 * User information
 */
// Define database table storage structure
const mongoose = require('./db');
const Schema = mongoose.Schema;

const UserSchema = new Schema({
  username: { type: String }, // User name
  password: { type: String }, // User password
  age: { type: String }, // User age
  lastLoinDate: { type: Date } // Last logon time
})

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

CRUD operation

3.1 insertion

Model#save([fn])
New test.js

const User = require('./user');

// insert
function insert() {
  var user = new User({
    username: "Chen Er dog", // User name
    password: "abc123", // User password
    age: 18, // User age
    lastLoinDate: new Date() // Last logon time
  });

  user.save(function (err, docs) {
    if(err) {
      console.log("Error: " + err);
    } else {
      console.log("docs: " + docs);
    }
  })
}
insert();

node test.js


3.2 update

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

// test1.js

const User = require('./user');

// To update
function update() {
  var whereStr = {"username": "Chen Er dog"};
  var updateStr = {"password": "123456"};

  User.update(whereStr, updateStr, function (err, docs) {
    if(err) {
      console.log("Error: " + err);
    } else {
      console.log("docs: " + docs);
    }
  })
}
update();

node test1.js

The common method is findByIdAndUpdate, which is specified according to _id.

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

// test12.js

const User = require('./user');

// Update according to ID 
function findByIdAndUpdate() {
  var id = "5b5333a114cf2d337c6bd971";
  var updateStr = {"password": "aabbcc"};

  User.findByIdAndUpdate(id, updateStr, function (err, docs) {
    if(err) {
      console.log("Error: " + err);
    } else {
      console.log("docs: " + docs);
    }
  })
}
findByIdAndUpdate();

Other update methods

Model.findOne AndUpdate ([conditions], [update], [options], [callback]) // Find a record and update it

3.3 delete

Model.remove(conditions, [callback])

// test2.js

const User = require('./user');

// delete 
function del() {
  var whereStr = {"username": "Chen Er dog"};

  User.remove(whereStr, function (err, docs) {
    if(err) {
      console.log("Error: " + err);
    } else {
      console.log("docs: " + docs);
    }
  })
}
del();

Other commonly used methods are:
  Model.findByIdAndRemove(id, [options], [callback])      
  Model.findOneAndRemove(conditions, [options], [callback])

3.4 Conditional Query

Some test data have been inserted first.

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

const User = require('./user');

// Conditional query
function getByConditions() {
  var whereStr = {"username": "Chen Er dog 1"};

  User.find(whereStr, function (err, docs) {
    if(err) {
      console.log("Error: " + err);
    } else {
      console.log("docs: " + docs);
    }
  })
}
getByConditions();

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

const User = require('./user');

// Conditional query (set the second parameter)
function getByConditions() {
  var whereStr = {"username": "Chen Er dog 1"};
  var opt = {"username": 1, "_id": 0};

  User.find(whereStr, opt, function (err, docs) {
    if(err) {
      console.log("Error: " + err);
    } else {
      console.log("docs: " + docs);
    }
  })
}
getByConditions();


The output will only have a username field, which is set as follows: 1 for query output, 0 for no output

3.4.1 Query Age

const User = require('./user');

// Conditional query
function getByConditions() {
  // var whereStr = {"username": "Chen Erguo 1"};
  // var opt = {"username": 1, "_id": 0};

  // User.find(whereStr, opt, function (err, docs) {
  // Query age is greater than 20 and less than or equal to 50
  User.find({"age": {$gte: 20, $lte: 50 }}, function (err, docs) {
    if(err) {
      console.log("Error: " + err);
    } else {
      console.log("docs: " + docs);
    }
  })
}
getByConditions();

3.4.2

or relationship
 Or negativity
 $gt >
More than or equal to $gte
 Less than $lt
 Less than or equal to
 $ne is not equal to
 In is in a range of values
 $nin is not in the range of multiple values
 Multiple values in the $all matching array
 $regex regular for fuzzy queries
 Matching array size
 maxDistance range query, distance (based on LBS)
mod
 near. Neighborhood query, query the location nearby (based on LBS)
Does the $exists field exist?
$elemMatch Matches the elements in the inner array
 within range query (based on LBS)
Range query, rectangular range (based on LBS)
center range alert, circular range (based on LBS)
Center Sphere Range Query, Spherical Range (LBS-based)
Slce: Query for elements in the field set (e.g. from the number after, N to M first elements)

3.5 Quantity Query


Model.count(conditions, [callback])

const User = require('./user');

// Quantity query
function getCountByConditions() {
  var whereStr = {};

  // User.count(whereStr, function (err, docs) {
  User.countDocuments(whereStr, function (err, docs) {
    if(err) {
      console.log("Error: " + err);
    } else {
      console.log("docs: " + docs);
    }
  })
}
getCountByConditions();


After amendment:

3.6 Query by _id

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

const User = require('./user');

// Query by _id
function getById () {
  var id = "5b536b314cfb3f0d54a53d37"

  User.findById(id, function (err, docs) {
    if(err) {
      console.log("Error: " + err);
    } else {
      console.log("docs: " + docs);
    }
  })
}
getById ();

3.7 Fuzzy Query

Additional data

const User = require('./user');

// Fuzzy query
// Find out that all user names have'm'names and are case-insensitive
function getByRegex () {
  var whereStr = {"username": {$regex: /m/i}};

  User.find(whereStr, function (err, docs) {
    if(err) {
      console.log("Error: " + err);
    } else {
      console.log("docs: " + docs);
    }
  })
}
getByRegex ();

3.8 Paging Query

const User = require('./user');

// Paging query
function getByPager () {
  var pageSize = 5; // How many items per page?
  var currentPage = 1; // What is the current page?
  var sort = {'lastLoinDate': -1}; // Reverse by login time
  var condition = {};
  var skipnum = (currentPage - 1) * pageSize; // Skipping number

  User.find(condition).skip(skipnum).limit(pageSize).sort(sort).exec(function (err, docs) {
    if(err) {
      console.log("Error: " + err);
    } else {
      console.log("docs: " + docs);
    }
  })
}
getByPager ();

CurrtPage = 1

CurrtPage = 2

3.9 Other Common Methods

Model.distinct(field, [conditions], [callback])  //Duplicate removal
Model.findOne(conditions, [fields], [options], [callback])   //Find a record
Model.findOneAndRemove(conditions, [options], [callback])  //Find a record and delete it
Model.findOneAndUpdate([conditions], [update], [options], [callback]) //Find a record and update it

Relevant Code Download

mongodb Learning (3) - NodeJs Manipulates mongodb with mongoose
mongoosejs









Keywords: Mongoose MongoDB less JSON

Added by chadt on Sat, 18 May 2019 07:37:48 +0300