/** * Created by Administrator on 2015/4/22. */var MongoDB = require ('./db '), BSON = require (' MongoDB '). Bsonpure;var user = function (user) {this.firstname = User.firstname; This.lastname = User.lastname;}; User.prototype.AddOne = function (callback) {var user = {FirstName:this.firstName, lastName:this.last Name}; Mongodb.open (err, db) {if (err) {return callback (ERR); } db.collection (' User ', function (err, collection) {if (err) {return callback (ERR); } collection.insert (user, {safe:true}, function (Err, n Ewuser) {mongodb.close (); if (ERR) {return callback (ERR); } callback (NULL, newuser[0]); } ) }); });}; User.prototype.UpdateById = function (ID, callback) {id = BSON. ObjectID. createfromhexstring (Id); var user = {firstName:this.firstName, lastName:this.lastName}; Mongodb.open (err, db) {if (err) {return callback (ERR); } db.collection (' User ', function (err, collection) {if (err) {mongodb.close (); Return callback (ERR); } collection.update ({_id:id}, user, {upsert:true, multi:false} , function (err, result) {mongodb.close (); if (ERR) {return callback (ERR); } callback (null, result); } ); }) });}; User.deletebyid = function (Id, callback) {if (! ID) {return; } Id = BSON. Objectid.createfromhexstring (ID); Mongodb.open (err, db) {if (err) {return callback (ERR); } db.collection(' User ', function (err, collection) {if (err) {mongodb.close (); Return callback (ERR); } collection.remove ({_id:id}, function (err, result) {mongodb.close (); if (ERR) {return callback (ERR); } return callback (null, result); }); }); });}; User.getall = function (callback) {Mongodb.open (function (err, db) {if (err) {return callback (ERR) ; } db.collection (' User ', function (err, collection) {if (err) {mongodb.close (); Return callback (ERR); } collection.find (). ToArray (function (err, docs) {mongodb.close (); if (ERR) {return callback (ERR); } callback (null, DOCS); }); }); });}; Module.exports = User;
Simple Nodejs + MongoDB CRUD