本文主要讲node是如何连接mongodb,并做基本的增删改查操作
mongodb的安装不多赘述,可参考菜鸟教程
mongodb与mysl的性能分析
本文参考地址: https://github.com/mongodb/node-mongodb-native
官方API文档:https://mongodb.github.io/node-mongodb-native/3.0/api/
本文项目环境: ubuntu16.04 node@v8.10.0 npm@6.1.0
- 创建项目路径
mkdir test_mongodb
- 初始化项目结构,并安装mongodb的依赖包
npm init
npm install mongodb --save
- 创建数据库目录并开启mongodb
mongod --dbpath=/data
- 创建app.js文件,并连接数据库myproject
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'myproject';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
assert.equal(null, err);
console.log("Connected successfully to server");
const db = client.db(dbName);
client.close();
});
执行命令可检测是否连接成功
node app.js
- 将多个数据插入文档
const insertDocuments = function(db, callback) {
// Get the documents collection
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);
});
}
其中,文档对应mysql中的表,在上段代码中文档名为documents,
将上述方法添加进app.js
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'myproject';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
assert.equal(null, err);
console.log("Connected successfully to server");
const db = client.db(dbName);
insertDocuments(db, function() {
client.close();
});
});
运行程序可查看返回结果
node app.js
- 查询所有文档
const findDocuments = function(db, callback) {
// Get the documents collection
const collection = db.collection('documents');
// Find some documents
collection.find({
}).toArray(function(err, docs) {
assert.equal(err, null);
console.log("Found the following records");
console.log(docs)
callback(docs);
});
}
find()方法中可添加查询条件,上述代码中为空,所以为查询所有文档,在app.js中添加该方法
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'myproject';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
assert

本文介绍了如何使用Node.js连接MongoDB并进行基础的数据库操作,包括连接数据库、创建文档、查询数据、更新和删除文档,以及使用async/await处理异步操作,提供了一个简单的MongoDB操作示例。
最低0.47元/天 解锁文章

被折叠的 条评论
为什么被折叠?



