Module manual encapsulation for mongodb operations
- 2020-06-19 11:57:56
- OfStack
Module manual encapsulation for mongodb operations
[Note] : This code is based on nodejs.
Create 1 module file *.js in the nodejs directory to call,
Here is the module code:
function mongodbModel(dbname,dataform) {
var MongoClient;
var DB_CONN_STR;
this.init = function() {
MongoClient = require('mongodb').MongoClient;
DB_CONN_STR = 'mongodb://localhost:27017/' + dbname;
}
/* So here's insert data */
this.insert = function(data,callback) {
MongoClient.connect(DB_CONN_STR, function(err, db) {
console.log(' The connection is successful ')
var collection = db.collection(dataform);
collection.insert(data, function(err,result){
callback(err,result);
})
})
}
/* This is deleting data */
this.remove = function(data,callback){
MongoClient.connect(DB_CONN_STR, function(err, db) {
console.log(' The connection is successful ')
var collection = db.collection(dataform);
collection.remove(data, function(err,result){
callback(err,result);
})
})
}
/* So here's the modification */
this.update=function(data,updata,callback){
MongoClient.connect(DB_CONN_STR, function(err, db) {
console.log(' The connection is successful ')
var collection = db.collection(dataform);
collection.update(data,updata,function(err,data){
callback(err,data);
})
})
}
/* So here's the query */
this.find=function(data,callback){
MongoClient.connect(DB_CONN_STR, function(err, db) {
console.log(' The connection is successful ')
var collection = db.collection(dataform);
collection.find(data).toArray(function(err,data){
callback(err,data);
})
})
}
}
module.exports = mongodbModel;
How to use:
Create 1 call file *.js in the same directory
var mongodbModel = require('./mongodbModel');
var mongodbObject = new mongodbModel('seraph','singer');
mongodbObject.init();
/* This is insertion */
mongodbObject.insert({name:' ah xx'},function(err,data){
if(err){
console.log(err);
}else{
console.log(data);
}
})
/* This is to remove */
mongodbObject.remove({name:' ah xiao'},function(err,data){
if(err){
console.log(err);
}else{
console.log(' The specified data was deleted successfully ');
}
})
/* So here's the modification */
mongodbObject.update({name:' Xiao li '},{$set:{name:' Xiao yong '}},function(err,data){
if(err){
console.log(err);
}else{
console.log(data);
}
})
/* Here's a conditional query */
mongodbObject.find({name:' Lee lok '},function(err,data){
if(err){
console.log(err);
}else{
console.log(data);
}
})
Relevant parameters:
dbname: means database to be operated;
dataform: Refers to the table of data to be manipulated;
data: Represents data that needs to be inserted or queried or modified;
updata: Represents the modified data;
callback() is a challenge when it comes to personal encapsulation
If you have any questions, please leave a message or go to this site community exchange discussion, thank you for reading, hope to help you, thank you for your support to this site!