一个简单的nodejs连接mongodb示例,来自 mongodb官方示例
1. 创建package.json
首先,创建我们的工程目录connect-mongodb,并作为我们的当前目录
mkdir connect-mongodb
cd connect-mongodb输入
npm init命令创建
package.json
npm init然后,安装mongodb的nodejs版本driver
npm install mongodb --savemongodb驱动包将会安装到当前目录下的node_modules中
2. 启动MongoDB服务器
安装MongoDB并启动MongoDB数据库服务,可参考我之前的文章,或者MongoDB官方文档
3. 连接MongoDB
创建一个app.js文件,并添加以下代码来连接服务器地址为192.168.0.243,mongodb端口为27017上名称为myNewDatabase的数据库
var MongoClient = require('mongodb').MongoClient,
assert = require('assert');
// Connection URL
var url = 'mongodb://192.168.0.243:27017/myNewDatabase';
MongoClient.connect(url,function(err,db){
assert.equal(null,err);
console.log("Connection successfully to server");
db.close();
});在命令行输入以下命令运行app.js
node app.js4. 插入文档
在app.js中添加以下代码,使用insertMany方法添加3个文档到documents集合中
var insertDocuments = function(db, callback){
// get ths documents collection
var collection = db.collection('documents');
// insert some documents
collection.insertMany([
{a:1},{a:2},{a:3}
],function(err,result){
assert.equal(err,null);
assert.equal(3,result.result.n);
assert.equal(3,result.ops.length);
console.log("Inserted 3 documents into the collection");
callback(result);
});
};insert命令返回一个包含以下属性的对象:
result MongoDB返回的文档结果
ops 添加了_id字段的文档
connection 执行插入操作所使用的connection
在app.js更新以下代码调用insertDocuments方法
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
// Connection URL
var url = 'mongodb://localhost:27017/myproject';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected successfully to server");
insertDocuments(db, function() {
db.close();
});
});在命令行中使用node app.js运行









