Basic use of mongoose

Keywords: Database Mongoose MongoDB less

There is nothing more necessary than to go through the official documents before we begin: http://mongoosejs.com/

What is mongoose? What's the use?
mongoose is an object model library for manipulating MongoDB; it encapsulates the common methods of document manipulation (add, delete and check) in MongoDB, which makes NodeJS operate Mongodb database quickly and flexibly.

The complete code used in this article: Source code

Install mongoose

New directories s4_mongoose and test.js files:

mkdir s4_mongoose
cd s4_mongoose
touch test.js

Initialize the directory to generate package.json and install mongoose:

npm init
cnpm install mongoose --save

Connect to the database

Edit test.js:

var mongoose = require('mongoose');
var db = mongoose.connect('mongodb://127.0.0.1:27017/test');
db.connection.on('error', function(error){
  console.log('data base test Connection failed:' + error);
});
db.connection.on('open', function(){
  console.log('data base test Successful connection');
});

Then open an iTerm2 terminal and open the mongodb service:

mongod

Open another iTerm2 terminal and run test.js:

node test.js
//When successful, the output will be: the database test connection is successful

Schema/Model/Entity

Nothing is more detailed than the documentation: http://mongoosejs.com/docs/guide.html

  1. Schema: The structural object of the database collection.

  2. Model: Constructed by Schema, operable database.

  3. Entity: An entity created by Model that operates a database.

After reading the document, look at the following code to understand:

var mongoose = require("mongoose");
var db = mongoose.connect("mongodb://127.0.0.1:27017/test");
// var testModel = db.model('test1', testSchema); // set name; set structure object
var TestSchema = new mongoose.Schema({
    name : { type:String },
    age  : { type:Number, default:0 },
    email: { type:String },
    time : { type:Date, default:Date.now }
});
var TestModel = db.model("test1", TestSchema );
var TestEntity = new TestModel({
    name : "helloworld",
    age  : 28,
    email: "helloworld@qq.com"
});
TestEntity.save(function(error,doc){
  if(error){
     console.log("error :" + error);
  }else{
     console.log(doc);
  }
});

model data insertion

On the premise that the previous database connection is successful, we create a new set test1 under the database test and insert a set of data into it:

var testSchema = new mongoose.Schema({
  name: {type: String},
  age: {type: Number, default: 0},
  email: {type: String},
  time: {type: Date, default: Date.now}
});
var testModel = db.model('test1', testSchema); // Collection name; the structure object of the collection
// Document document (associative array object) < Collection collection < database
// Insert and save a piece of data
testModel.create([
  {name: "test1", age: 8},
  {name: "test2", age: 18},
  {name: "test3", age: 28},
  {name: "test4", age: 38},
  {name: "test5", age: 48},
  {name: "test6", age: 58, email:"tttt@qq.com"},
  {name: "test7", age: 68, email:"ssss@qq.com"},
  {name: "test8", age: 18},
  {name: "test9", age: 18, email:"rrrr@qq.com"},
  {name: "test10",age: 18}
], function (error, docs) {
  if(error) {
    console.log(error);
  } else {
    console.log('save ok');
    console.log(docs);
  }
});

find Data Query

mongoose provides find, findOne, and findById methods for document queries.
Basic grammar:

model.find(Conditions,fields,options,callback(err, doc));

Conditions: Query conditions
Fields: returned fields
options: sort,limit
callback: callback function, parameter doc is the result of the query

The basis of conditional query:
lt (less than <)
$lt e (less than or equal to <=)
$gt (greater than >)
gte (greater than or equal to >=)
$ne (not equal to, not included!=)
$in (including)
$or (queries for any given value of multiple key values)
exists
$all (all)

Specific examples, the code has detailed comments:

// find(Conditions,fields,callback);
// Omit or empty, return all records; only include name,age fields, remove default _id fields; execute callback functions
testModel.find({}, {name:1, age:1, _id:0}, function(err, docs){
  if (err) {
    console.log('Query error:' + err);
  } else {
    console.log('{}The results of the query are as follows:');
    console.log(docs);
  }
});
// Query age greater than or equal to 28, less than or equal to 48
testModel.find({age: {$gte: 28, $lte: 48}}, {name:1, age:1, _id:0}, function(err, docs){
  if (err) {
    console.log('Query error:' + err);
  } else {
    console.log('$gte,$lte The results of the query are as follows:');
    console.log(docs);
  }
});
// Query age for 28, 68 items of data
testModel.find({age: {$in: [58, 68]}}, {name:1, age:1, _id:0}, function(err, docs){
  if (err) {
    console.log('Query error:' + err);
  } else {
    console.log('$in The results of the query are as follows:');
    console.log(docs);
  }
});
// Query all data whose name is test3 or age is 18
testModel.find({$or: [{name: 'test3'}, {age: 18}]}, {name:1, age:1, _id:0}, function(err, docs){
  if (err) {
    console.log('Query error:' + err);
  } else {
    console.log('$or The results of the query are as follows:');
    console.log(docs);
  }
});

// Step 3: cursor query
// Query all data whose name is test3 or age is 18; however, there is a limit to querying only two data
testModel.find({$or: [{name: 'test3'}, {age: 18}]}, {name:1, age:1, _id:0}, {limit: 2}, function(err, docs){
  if (err) {
    console.log('Query error:' + err);
  } else {
    console.log('limit The results of the query are as follows:');
    console.log(docs);
  }
});

Update data update

Basic use: model. update (query condition, update object, callback);

var conditions = {name: 'test1'};
var update = {$set: {age: 11 }};
testModel.update(conditions, update, function(error){
  if(error) {
    console.log(error);
  } else {
    console.log('Update success!');
    testModel.find({name: 'test1'}, {name:1, age:1, _id:0}, function(err, docs){
      if (err) {
        console.log('Query error:' + err);
      } else {
        console.log('To update test1 The results of the query are as follows:');
        console.log(docs);  // After updating test_update, the query result is an empty array: [];
                            // The query result after updating test1 is: [{name:'test1', age: 11}]
                            // Only existing data can be updated
      }
    });
  }
});

remove data deletion

Basic use: model. remove (query condition, callback);

var conditions = {name: 'test2'};
testModel.remove(conditions, function(error){
  if(error) {
    console.log(error);
  } else {
    console.log('Delete success!');
    testModel.find({name: 'test2'}, {name:1, age:1, _id:0}, function(err, docs){
      if (err) {
        console.log('Query error:' + err);
      } else {
        console.log('delete test2 The results of the query are as follows:');
        console.log(docs);  // After deleting test2, the query result is an empty array: [];
      }
    });
  }
});

robomongo mongodb visualization tool

Install mongodb visualization tool robomongo
After iTerm2 opens the local mongodb (execute mongod), open robomongo, and create a new connection to connect to the local mongodb database.

Posted by s.prema@yahoo.com on Sun, 09 Jun 2019 12:57:29 -0700