Home > Web Front-end > JS Tutorial > body text

How to operate mongodb's fill, delete, modify, and query module using nodejs

亚连
Release: 2018-06-14 11:25:07
Original
1445 people have browsed it

Below I will share with you an example of the production and introduction of the nodejs operation mongodb fill, delete, modify and check module. It has a good reference value and I hope it will be helpful to everyone.

Install related modules

If you use this, you need to install the required modules yourself first and enter

in the root directory
npm install mongodb --save
Copy after login

Install the module. After the installation is successful, you can proceed with the following steps.

Introduction of files

The following is the relevant code I wrote, put it in the relevant directory that you can quote, I put it in the root of express Directory

function Mongo(options) {
 this.settings = {
  url: 'mongodb://localhost:27017/jk',
  MongoClient:require('mongodb').MongoClient,
  assert:require('assert')
 };
 for(let i in options){
  this.settings[i] = options[i];
 }
 this._run = function (fun) {
  let that = this;
  let settings = this.settings;
  this.settings.MongoClient.connect(this.settings.url, function (err, db) {
   settings.assert.equal(null, err);
   console.log("Connected correctly to server");
   fun(db, function () {
    db.close();
   });
  });
 };
 this.insert = function (collectionName, data, func) {
  //增加数据
  let insertDocuments = function (db, callback) {
   let collection = db.collection(collectionName);
   collection.insertMany([
    data
   ], function (err, result) {
    if (!err) {
     func(true);
    } else {
     func(false);
    }
    callback(result);
   });
  };
  this._run(insertDocuments);
 };
 this.update = function (collectionName, updateData, data, func) {
  //更新数据
  let updateDocument = function (db, callback) {
   let collection = db.collection(collectionName);
   collection.updateOne(updateData
    , {$set: data}, function (err, result) {
     if (!err) {
      func(true);
     } else {
      func(false);
     }
     callback(result);
    });
  };
  this._run(updateDocument);
 };
 this.delete = function (collectionName, data, func) {
  //删除数据
  let deleteDocument = function (db, callback) {
   let collection = db.collection(collectionName);
   collection.deleteOne(data, function (err, result) {
    if (!err) {
     func(true);
    } else {
     func(false);
    }
    callback(result);
   });
  };
  this._run(deleteDocument);
 };
 this.find = function (collectionName, data, func) {
  //查找数据
  let findDocuments = function (db, callback) {
   // Get the documents collection
   let collection = db.collection(collectionName);
   // Find some documents
   collection.find(data).toArray(function (err, docs) {
    if (!err) {
     func(true,docs);
    }
    else {
     func(false, err);
    }
    callback(docs);
   });
  };
  this._run(findDocuments);
 };
}
module.exports = Mongo;
Copy after login

I saved it in a file named server.js

Use

We need Use the page to first introduce the module. For example, I introduced it in the routing file index.js:

const Server = require("../server.js");
Copy after login

Then you need to instantiate the object, as follows:

let server = new Server();
Copy after login

If you need to configure related Information can be passed in an object configuration when instantiating, and the address of the database can be configured:

let server = new Server({url:"mongodb://localhost:27017/mydb"});
Copy after login

There are four methods encapsulated in it, add, delete, modify and check, respectively

Add method

##server.insert(data table name, data to be inserted (key-value pair object), callback function);

Update method##server.update(data table name, queried data (object), updated data (object), callback function);

Delete methodserver.delete(data table name, queried data (object), callback function);

Find methodserver.find(data table name, queried data (object), callback function);

The callback function will return two Value, the first Boolean type, whether the processing is successful, the second value, the search returns the number found, and the others return the number of successful processing (now only one is processed at a time)

Use case

For example, if I need to find data in a route, I need this:

server.find("users",{username:"username"},function (bool,data) {
  if(bool){
   console.log("查询到数据为"+data.length+"条");
  }
  else{
   console.log(data);
  }
 });
});
Copy after login

The above code queries the data of the field where username is username in the users table. If successful, data will return an array later. If an error occurs, data error will be returned directly.

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

MySQL changes root password

How to write quality JS code

Related usage of js array reduce

The above is the detailed content of How to operate mongodb's fill, delete, modify, and query module using nodejs. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template