Using Node to operate MongoDB

1. Use MongoDB module for operation

First, install the mongodb module in the working directory,

1 cnpm i mongodb//Lead in module
const MongoClient = require('mongodb').MongoClient;
//Write connection string,My database address is as follows,So when you're writing, just change the address
const DB_CONN_STR= 'mongodb://127.0.0.1/demo';
//Remember to open it mongod service ,Or wait for a bunch err bar

//Write a function to insert data
const insertData = function(db,callback){
    let collection = db.collection('Collection name');
    
    let data = [{"name":"AAA","age":"19"},{"name":"BBB","age":"20"}]
     // Add data to collection
    collection.insert(data,function(err,result){
        if(err){
            console.log('Error'+err);
            return;
        }
        callback(result);
    });   
}
//Connect to database Connection string Callback function MongoClient.connect(DB_CONN_STR, function(err, db) { console.log("Done"); //Call the function just written insertData(db, function(result) { //Output return result console.log(result); //Close connection db.close(); }); });
2. Use Mongoose module for operation
2.1 create the file db.js to connect (in fact, there is a little problem in this step, so the database connection should not be written here)
//create a file db.js
// You should have installed it before that mongoose || cnpm install mongoose
// And it's turned on mongod service 
import  mongoose from 'mongoose';
//mongoose.connect('mongodb://127.0.0.1:27017/demo'); 
//If it's just the address,There will be a warning,It's not a mistake,Only belongs to the writing method that is not recommended.It is recommended to write as follows
mongoose.connect('mongodb://Address / database name ', {useMongoClient: true});
const db = mongoose.connection;
// 
db.on('error',console.error.bind(console,'connection error:'));

db.once('open',function(callback){
     console.log("connection start");
});
db.on('disconnected',function(){
   console.log("connstion is disconnected");
});

module.exports = mongoose;

 2.2 Shema 

Create file stu.js save operation

Everything in Mongoose comes from Schema. Each Schema maps to a MongoDB collection and defines the shape (type) of the documents in that collection.
// As shown in the name,What we're going to create is a user Of Schmea
//If you want to add another key later, use the Schema.add({})method.
//Introduce the module just written
import mongoose from './db'
const Shema = mongoose.Schema;
const UserShema = new Schema({
    name : {type:String},
    age : {type:Number},
    class : {type:String}
})

// Schema Types The built-in types are as follows:
// String,Number,Boolean | Bool,Array,Buffer,Date,ObjectId | Oid,Mixed
// If you find out what attributes are missing,have access to Shame.add();Append
UserShema.add{mail : 'String',pwd : 'String'}
// Then use Schema Create our model ,Add to module again,This step is very important
module.exports = mongoose.model('Student',UserSchema)

2.3 use of Shema (added)

//
//
stay import user.js It's time to start mongoose.model('Classes',ClassSchema);See the last code above import student from './stu' class mannager{ //The first way to create add(){ let newStu = new student({ name : 'Zhang San', age : 25, class : 'Senior' }); newStu.save(function (err) { if (err) return handleError(err); }); } //The second way to create add2(){ student.create({ name : 'Zhang San', age : 25, class : 'Senior' },function(err){ if (err) return handleError(err); }); }     }

Use of Shema (query)

 mongoose
Support rich query MongoDB syntax. Files can use find, findById, findOne, or where, static methods in each model.

 

 //Query all
    findAll(){
      return student.find(function(err,res){
            if (err) {
                return err;
            }else{
                let json = JSON.stringify(res); 
                return res;
            }
        });
    }
    //Query by criteria
    findByAge(age){
        return student.find({Age : age},function(err,res){
            if (err) {
                return err;
            }else{
                let json = JSON.stringify(res); 
                return res;
            }
        });
    }
    //Multiple conditions
    findTest(){
        return Tank.find(
            { class: 'Junior' }).where('Age').gt(20).exec(callback);
    }

 

 

The API documentation contains many additional methods, such as countmapReduceaggregateMore . I don't want to raise chestnuts here

 

 

 

 

Tags: Javascript Mongoose MongoDB Database JSON

Posted on Sat, 02 May 2020 15:31:39 -0700 by daimoore