一、安装好mongodb与配置好mongodb服务后,创建数据库mytest,再在此数据库下创建用户lzy。
db.createUser({user:"lzy",pwd:"lzy",roles:[{role:"readWrite",db:"mytest"}]})
创建完用户后,需要给用户认证。
方法一:mongod -u lzy -p lzy --authenticationDatabase mytest
如果方法一认证不通过,可以使用方法二
方法二:用--auth启动mongod 如:mongod --auth
再用db.auth()方法认证 如:db.auth("lzy":"lzy")
二、node程序
var Db = require('mongodb').Db; var Server = require('mongodb').Server; var http = require('http'); /*数据库连接信息host,port,user,pwd*/ var db_name = 'mytest'; //数据库名称 var db_host = '127.0.0.1'; //数据库地址 var db_port = '27017'; // 数据库端口 var username = 'lzy'; //用户名,如:lzy var password = 'lzy'; //用户密码,如:lzy var db = new Db(db_name, new Server(db_host, db_port, {}), { w: 1 }); //启动时建立连接 db.open(function(err, db) { db.authenticate(username, password, function(err, result) { if (err) { db.close(); console.log('链接失败'); return; } console.log("链接成功"); }); }); var port = 5050; //每次来请求时复用已有连接执行query,如果连接已被server端断开底层驱动会自动重连 http.createServer(function(request, response) { function test(err, collection) { collection.insert({ id: 101, name:'张三' }, function(err, docs) { if (err) { console.log(err); response.end('插入失败'); return; } collection.count(function(err, count) { if (err) { console.log(err); response.end('count error'); return; } response.end('插入: ' + count + '条记录\n'); }); }); } //插入到user文档 db.collection("user", test); }).listen(port); console.log("端口在:"+port);
再用node命令启动,该程序
如果出现该错误
module.js:471
throw err;
^
Error: Cannot find module 'mongodb'
at Function.Module._resolveFilename (module.js:469:15)
at Function.Module._load (module.js:417:25)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (E:\Project\myCode\study\MongoDB\nodeConnectionMongoDB\connServer.js:1:90)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
Program node connServer.js exited with code 1
Starting child process with 'node connServer.js'
throw err;
^
Error: Cannot find module 'mongodb'
at Function.Module._resolveFilename (module.js:469:15)
at Function.Module._load (module.js:417:25)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (E:\Project\myCode\study\MongoDB\nodeConnectionMongoDB\connServer.js:1:90)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
Program node connServer.js exited with code 1
Starting child process with 'node connServer.js'
说明mongodb依赖没有加进来
解决方法:
1、可以通过npm命令加载依赖,如:在该项目下
npm install mongodb 如果你安装了淘宝镜像可以使用: cnpm install mongodb
2、在全局下安装npm install mongodb -g 或使用: cnpm install mongodb -g
再通过 npm link mongodb,这样运行node脚本时会通过此链接找到mongodb的模块module.js
最后,打开浏览器访问http://localhost:5050