天天看點

Nodejs通路MongoDB

Setting.js[用于儲存資料庫資訊]

module.exports = {
	name : 'ZMessage',
	host : 'localhost'
}
      

 name為資料庫名稱,host為資料庫通路位址。

DBHelper.js[具體通路資料庫的方法]

function DBHelper(){
	this.dbSetting = require('./DBSettings.js');
	this.Db = require('mongodb').Db;
	this.Connection = require('mongodb').Connection;
	this.Server = require('mongodb').Server;
	this.GetDBExecutor = function(){
		return new this.Db(this.dbSetting.name, new this.Server(this.dbSetting.host, this.Connection.DEFAULT_PORT, {}),{safe:false});
	};
	//擷取所有使用者資訊
	this.getAllUser = function(callback){
		var executor = this.GetDBExecutor();
		executor.open(function(err, db) {
			if (err) {
				return callback(err);
			}
			db.collection('UserInfo', function(err, collection) {
				if (err) {
					executor.close();
					return callback(err);
				}
				collection.find({}).toArray(function(err,items){
					executor.close();
					items.forEach(function(item, index) {
						console.log(item.userName);
					});
				});
			});
		});
	}
	
	//添加使用者資訊
	this.addUser = function(user,callback){
		var executor = this.GetDBExecutor();
		executor.open(function(err, db) {
			if (err) {
				return callback(err);
			}
			db.collection('UserInfo', function(err, collection) {
				console.log(4);
				if (err) {
					executor.close();
					return callback(err);
				}
				collection.insert(user, {safe: true}, function(err, user) {
					executor.close();	
				});
			});
		});
	}
	
	//添加使用者資訊
	this.updateUser = function(user, callback){
		var executor = this.GetDBExecutor();
		executor.open(function(err, db){
			if (err) {
				return callback(err);
			}
			db.collection('UserInfo', function(err, collection){
				if (err) {
					executor.close();
					return callback(err);
				}
				collection.update({
					"userId": user.userId
				}, {
					$set: {
						userName: "更改後"
					}
				}, {
					saft: false,
					upsert: true
				}, function(err, user){
					executor.close();
				});
			});
		});
	}
	//删除使用者資訊
	this.deleteUser = function(userId,callback){
		var executor = this.GetDBExecutor();
		executor.open(function(err, db) {
			if (err) {
				return callback(err);
			}
			db.collection('UserInfo', function(err, collection) {
				if (err) {
					executor.close();
					return callback(err);
				}
				collection.remove({"userId":userId},{saft:false},function(err, user) {
					executor.close();	
				});
			});
		});
	}
}
module.exports = new DBHelper();      

 假設已經存在UserInfo集合。

app.js啟動檔案用于測試

var dbclient = require('./DBHelper/DBHelper');

dbclient.addUser({userId:3,userName:'李四',userStatus : false},function(err){
	console.log(err);
});

dbclient.getAllUser(function(err){
	console.log(err);
});

dbclient.updateUser({userId:3,userName:'李四',userStatus : true},function(err){
	console.log(err);
});

dbclient.deleteUser(3,function(err){
	console.log(err);
});      

關于更新,有幾種更新方式

Fields

Name Description
$inc Increments the value of the field by the specified amount.
$rename Renames a field.
$setOnInsert Sets the value of a field upon documentation creation during an upsert. Has no effect on update operations that modify existing documents.
$set Sets the value of a field in an existing document.
$unset Removes the specified field from an existing document.

Array

Operators

Name Description
$ Acts as a placeholder to update the first element that matches the query condition in an update.
$addToSet Adds elements to an existing array only if they do not already exist in the set.
$pop Removes the first or last item of an array.
$pullAll Removes multiple values from an array.
$pull Removes items from an array that match a query statement.
$pushAll Deprecated. Adds several items to an array.
$push Adds an item to an array.

Modifiers

Name Description
$each Modifies the $push and $addToSet operators to append multiple items for array updates.
$slice Modifies the $push operator to limit the size of updated arrays.
$sort Modifies the $push operator to reorder documents stored in an array.

Bitwise

Name Description
$bit Performs bitwise AND and OR updates of integer values.

Isolation

Name Description
$isolated Modifies behavior of multi-updates to improve the isolation of the operation.