nodejs操作mongodb的填删改查模块的制作及引入

安装相关模块

如果使用这个的话,你需要先自己安装一下他需要的模块,在根目录输入

npm install mongodb --save
 
 
  • 1

进行模块安装,安装成功以后就可以进行以下的步骤。

文件的引入

以下是我书写的相关代码,放到你可以引用的相关目录,本人放到了express的根目录


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;

 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102

我存入到了一个名字叫server.js的文件名内

使用

我们在需要使用页面先将模块引入,比如我在路由文件index.js里面引入:

const Server = require("../server.js");
 
 
  • 1

然后需要实例化对象,如下:

let server = new Server();
 
 
  • 1

如果需要配置相关信息,可以在实例化的时候传入一个对象配置,可以配置数据库的地址:

let server = new Server({url:"mongodb://localhost:27017/mydb"});
 
 
  • 1

里面封装了四个方法,添删改查,分别是 
添加方法

server.insert(数据表名,需要插入的数据(键值对的对象),回调函数);
 
 
  • 1

更新方法

server.update(数据表名,查询的数据(对象),更新的数据(对象),回调函数);
 
 
  • 1

删除方法

server.delete(数据表名,查询的数据(对象),回调函数);
 
 
  • 1

查找方法

server.find(数据表名,查询的数据(对象),回调函数);
 
 
  • 1

回调函数都会返回两个值,第一个布尔类型,是否处理成功,第二个值,查找返回查找到的个数,别的都返回处理成功的个数(现在一次只处理一条)

使用案例

比如我需要在一个路由里面查找数据,我就需要这样:

server.find("users",{username:"username"},function (bool,data) {
        if(bool){
            console.log("查询到数据为"+data.length+"条");
        }
        else{
            console.log(data);
        }
    });
});
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

上面的代码是查询了users表里面username为username的字段的数据,如果成功,后面data就会返回一个数组,如果出现错误,就直接返回data错误。

转载自:http://blog.csdn.net/qq_30100043/article/details/77430961

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Node.js提供了许多不同的方式来操作MongoDB数据库。以下是其中一些常见的方法: 1.使用官方的MongoDB Node.js驱动程序 可以使用官方的MongoDB Node.js驱动程序来连接和操作MongoDB数据库。这个驱动程序提供了许多不同的方法和选项,可以满足不同的需求。以下是一个简单的例子,展示如何使用官方驱动程序连接到MongoDB数据库,并执行简单的操作: ``` const MongoClient = require('mongodb').MongoClient; // Connection URL const url = 'mongodb://localhost:27017'; // Database Name const dbName = 'myproject'; // Use connect method to connect to the server MongoClient.connect(url, function(err, client) { console.log("Connected successfully to server"); const db = client.db(dbName); // Find some documents db.collection('users').find({}).toArray(function(err, docs) { console.log("Found the following records"); console.log(docs); client.close(); }); }); ``` 2.使用Mongoose库 Mongoose是一个MongoDB对象模型工具,它提供了一种更简单的方式来操作MongoDB数据库。它允许您定义模式和模型,以便更轻松地执行常见的操作,如插入、更新和询文档。以下是一个例子,展示如何使用Mongoose连接到MongoDB数据库,并定义一个简单的用户模型: ``` const mongoose = require('mongoose'); // Connection URL const url = 'mongodb://localhost:27017/myproject'; // Connect to the database mongoose.connect(url, {useNewUrlParser: true}); // Define a schema const userSchema = new mongoose.Schema({ name: String, email: String, age: Number }); // Define a model const User = mongoose.model('User', userSchema); // Create a new user const user = new User({ name: 'John Smith', email: '[email protected]', age: 30 }); // Save the user to the database user.save(function(err) { if (err) throw err; // Find all users User.find(function(err, users) { if (err) throw err; console.log(users); mongoose.connection.close(); }); }); ``` 3.使用第三方库 除了官方驱动程序和Mongoose之外,还有许多其他的Node.js库可以用于操作MongoDB数据库。一些流行的库包括MongoDB Native、mongojs和Monk。这些库提供了不同的API和功能,可以满足不同的需求。以下是一个例子,展示如何使用mongojs库连接到MongoDB数据库,并执行简单的操作: ``` const mongojs = require('mongojs'); // Connection URL const url = 'mongodb://localhost:27017/myproject'; // Connect to the database const db = mongojs(url, ['users']); // Find all users db.users.find(function(err, users) { if (err) throw err; console.log(users); db.close(); }); ``` 无论您选择使用哪种方法,Node.js提供了许多选项和库,可以帮助您轻松地操作MongoDB数据库。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值