http://mongodb.github.io/node-mongodb-native/3.1/quick-start/quick-start/
一、安装使用mongodb库
- 安装
npm install mongodb --save
- 引入 mongodb 下的MongoClient
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
- 定义数据库连接的地址以及配置数据库名称
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'myproject';
- nodejs连接数据库
// Create a new MongoClient
const client = new MongoClient(url);
// Use connect method to connect to the Server
client.connect(function(err) {
assert.equal(null, err);//如果没有报错
console.log("Connected successfully to server");
const db = client.db(dbName);
client.close();
});
- 操作
const 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);
});