node与mongodb的使用

1、mongdb安装好后,在.bin文件夹下执行mongod.exe --dbpath=D:\mongodb\db  即可启动mongodb,表示将数据放在db这个文件夹,且每一次启动要执行完整的这句话。

启动完成后访问127.0.0.1:27017,如果出现‘It looks like you are trying to access MongoDB over HTTP on the native driver port.’ 字样表示启动成功,再重新打开一个控制台mongo进入数据库便可以进行数据操作。

2、nodejs连接mongodb

     先npm install mongodb 安装包

    然后:

  

var mongodb =require('mongodb');
var server = new mongodb.Server('localhost', 27017, {auto_reconnect:true});
var db = new mongodb.Db('test', server, {safe:true});
db.open(function(err, db){
    if(!err){
        console.log('connect');
        db.createCollection('person',{safe:true},function(err,collection){
            collection.find().toArray(function(err,docs){
                console.log('find');
                console.log(docs);
            });
            collection.insert({name:'lmy',age:18},{safe:true},function(err,result){
                console.log(result);
            });
            collection.find().toArray(function(err,docs){
                console.log('find');
                console.log(docs);
            });
        })
    }else{
        console.log(err);
    }
});

便可以操作数据库,执行上面一段代码,数据库中便会插入一条数据。

posted @ 2016-12-16 10:44  lmy2016  阅读(195)  评论(0编辑  收藏  举报