How to use mongodb database in node.js

Posted by Walker33 on Thu, 02 Apr 2020 11:33:27 +0200

This paper introduces the usage of mongodb database in node.js project. The related directory structure is the directory in the project. The code is not uploaded first, only the method is introduced.

Using mongodb for database

The installation method of mongodb server is to execute apt get install mongodb in ubuntu, and execute / etc/init.d/mongodb start after the installation is successful.

The component to be added in nodejs is mongoose, which has built-in mongodb client components.

Directory file

  • /config/mongoose.js to call the database entry and connect to the database
  • /Address of config/db_url.js database
  • /Model / encapsulate database data model

API of database

1. / config/db_url.js

module.exports={
    mongodb:"mongodb://localhost/company_website"
}

2. Each JS file in the / model / directory defines the data model of the database, such as demo.js

var mongoose=require('mongoose');
//New model
var  demo=new mongoose.Schema({
    username:String,
    password:String,
    status:String
});
//Encapsulation attribute interface
mongoose.model('Demo',demo);

3, calling /config/db_url.js in /config/mongoose.js and connecting to the database, loading the database data model.

var mongoose=require('mongoose');
var config=require('./db_url.js');
//Initialization function
module.exports=function(){
    var db=mongoose.connect(config.mongodb);
    require('../model/demo.js');
    return db;
}

4. Call /config/mongoose.js in app.js to initialize the database connection.

var mongoose=require('./config/mongoose.js');
//Initialization
var db=mongoose();

5. Database query / add / delete, take demo as an example

var mongoose=require('mongoose');
var Demo=mongoose.model('Demo');
//Query username
var username="admin";
User.findOne({username:username},function(err,doc){
    if(err){
        console.log('error');
    }
    else if(doc==null){
        console.log('not exist');
    }
    else{
        //Modify the properties of queried objects
        doc.status='1';
        doc.save(function(err){
            if(err){
                console.log('error');
            }else{
                console.log('success');
            }
        })
    }
});

//Create a demo object
var demo=new Demo(
    {
        username:username,
        password:password,
        status:'0'
    }
);
Demo.create(demo,function(err,doc){
    if(err){
        console.log('error');
    }
    console.log('success');
}); 

//delete object
var id="xxxx";
Demo.remove({_id:id},function(err,doc){
    if(err){
        console.log('error');
    }else{
        console.log('success');
    }
});

Topics: Mongoose Database MongoDB Ubuntu