/* * 在MongoDB数据库中插入数据 * */var mongo = require('mongoDB');var host = 'localhost';var port = 27017;//var port = mongo.Connection.DEFAULT_PORT;//创建mongoDB数据库所在服务器的Server对象,用于指定需要链接的MongoDB所在的服务器var server = new mongo.Server(host,port,{auto_reconnect : true});//创建一个代表MongoDB数据库额的DB对象var db = new mongo.Db('node-mongo-examples',server,{safe : true});var person1 = {username:'三',firstname:'张'};var person2 = {username:'四',firstname:'李'};var person3 = {username:'五',firstname:'王'};db.open(function (err, db) { //访问一个集合 //db.collection(collectionName,[options],[callback]) function(err,collection){} db.collection('user',function (err, collection) { //insert方法将数据文档插入集合中 //collection.insert(docs,[options],[callback]) function(err,docs){} collection.insert({username:'js',age:21},function (err, docs) { //collection.insert(person3,function (err, docs) { //collection.insert(person2,function (err, docs) { //collection.insert(person1,function (err, docs) { console.log(docs); //close方法 //close([forceClose],[callback]) //forceClose为是否强制关闭数据库。默认为false。 //false:关闭后还能用open()方法打开 true:关闭后不可用用open()方法打开 db.close(); }); });});