jsnjzlw 发表于 2015-7-6 11:08:55

win下node-mongodb-native操作mongodb

  nodejs win下没有npm功能,应用各种库文件相当杯具,这里用了node-mongodb-native在win下操作mongodb,小D很菜,对nodejs各种不懂,勉强简单封装了个对mongodb的curd操作,,,,
  首先去下载https://github.com/christkv/node-mongodb-native,把文件lib下的东西放到了如下目录

  如何操作看他的文档吧,e文不行的估计看例子也能看个大概....下面是封装代码mghp.js


View Code


var mongodb = require('./refLib/mongodb');
var _server = function(mongoCollection, mongoDB) {
    var sv = new mongodb.Server('127.0.0.1', 27017, {});
    this.mongoCollection = mongoCollection || 'nodeCollection';
    this.mongoDB = mongoDB || 'nodeDB';
    this.db = new mongodb.Db(this.mongoDB, sv, {});
}
_server.prototype.Open = function(callback) {
    var that = this;
    if (that.db && that.db.state == 'connected') {
      callback && callback();
    } else {
      that.db.open(function(error, client) {
            if (error) throw error;
            that.collection = new mongodb.Collection(client, that.mongoCollection);
            callback && callback();
      });
    }
}
_server.prototype.Close = function(isClose) {
    if (!!isClose && this.db) {
      this.db.close();
      this.collection = null;
      this.db = null;
    }
}
_server.prototype.Insert = function(obj, func, isClose) {
    var that = this;
    that.Open(function() {
      that.collection.insert(obj, { safe: true }, function(err) {
            that.Close(isClose);
            if (err) {
                console.warn(err.message);
            }
            if (err && err.message.indexOf('E11000') !== -1) {
                //this _id was already inserted in the database
            }
            func && func();
      });
    });
}

_server.prototype.Find = function(obj, func, isClose) {
    var that = this;
    that.Open(function() {
      that.collection.find(obj, function(err, cursor) {
            that.Close(isClose);
            if (err) {
                console.warn(err.message);
            }
            cursor.toArray(function(err, items) {
                func && func(items);
            });
      });
    });
}
_server.prototype.Update = function(obj, objN, func, isClose) {
    var that = this;
    that.Open(function() {
      that.collection.update(obj, { $set: objN }, { safe: true }, function(err) {
            that.Close(isClose);
            if (err) {
                console.warn(err.message);
            }
            func && func();
      });
    });
}
_server.prototype.Remove = function(obj, func, isClose) {
    var that = this;
    that.Open(function() {
      that.collection.remove(obj, function(err, result) {
            that.Close(isClose);
            if (err) {
                console.warn(err.message);
            }
            func && func(result);
      });
    });
}
exports.Server = _server;

  因为是异步的所以连续操作的话要放在回调函数中,方法还有第三个参数,如果是true则关闭链接
  s.Insert({ "ID": "10001", "name": "ygm" }, function() {
  ....
  },true);
  查看操作结果
页: [1]
查看完整版本: win下node-mongodb-native操作mongodb