nodejs使用mongodb驱动操作mongodb
一、简介
node.js 下操作 mongodb
有多个库可以选择,最原始的方式就是使用 npm 的 mongdodb
库。
mongodb github 地址:
API文档地址:
实际项目中基本不会使用 mongodb 库了,比较推荐的是 mongosee
和 mongoskin
。
因此只是了解一下 mongodb 的主要操作方法。
CRUD操作
二、连接数据库
assert 只是用来判断错误的断言。
基于 mongodb 的回调机制,因此在拿到 db
之后,在进行所有的操作,而所有的操作都应当在 connect
的回调中进行触发。
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
// 数据库地址
const url = 'mongodb://192.168.158.128:27017';
// 数据库名称
const dbName = 'test';
// 启动连接
MongoClient.connect(url, (err, client) => {
assert.equal(null, err);
const db = client.db(dbName);
// 之后的操作都在这里面
});
三、查询数据
mongodb 3.0
是支持 promise
操作的,因此可以通过 Promise 的语法更好的管理代码。
1、查询一条数据 findOne
操作方法:
function findOneDocument(db,callback){
// 拿到 collection
const collection = db.collection('user');
collection.findOne({sn:1}).then((res)=>{
callback(res);
});
}
使用方法:
MongoClient.connect(url, (err, client) => {
assert.equal(null, err);
const db = client.db(dbName);
// 查找一个文档
findOneDocument(db, (docs)=>{
console.log(docs);
// 每次使用完之后需要关闭连接
client.close();
});
// 结果如果是空,返回 null
});
2、查询多条数据 find
查找多个文档可以通过 toArray()
转换成数组,同时也支持 promise 操作。
function findManyDocument(db, callback){
const collection = db.collection('user');
collection.find({}).limit(3).toArray().then((res)=>{
callback(res);
});
}
结果示例:
[ { _id: 5afa967370327d0229409491, sn: 0, name: 'ptbird0' },
{ _id: 5afa967370327d0229409493, sn: 2, name: 'ptbird2' },
{ _id: 5afa967370327d0229409494, sn: 3, name: 'ptbird3' } ]
四、插入数据
1、插入一条数据 insertOne
结果中,可以通过 res.result
查看, ok = 1
表示成功,而 n
表示影响的行数
结果:{ ok: 1, n: 1 }
function insertDocument(db, callback) {
const collection = db.collection('user');
collection.insertOne({
sn:1,
name:'newptbird'
}).then((res)=>{
callback(res);
});
}
2、插入多条数据 insertMany
插入结果:
{ ok: 1, n: 3 }
function insertManyDocument(db,callback){
const collection = db.collection('user');
collection.insertMany([
{sn:1,name:'ptbirdss'},
{sn:2,name:'ptbirdss'},
{sn:3,name:'ptbirdss'},
]).then((res)=>{
callback(res);
});
}
五、更新
1、更新一条数据 updateOne
{ ok: 1, n: 1 }
function updateOneDocument(db,callback){
const collection = db.collection('user');
collection.updateOne({sn:1},{$set:{name:'newptbird11111'}}).then((res)=>{
callback(res);
}).catch((err)=>{console.log(err)});
}
2、更新多条数据 updateMany
{ ok: 1, n: 3 }
function updateManyDocument(db,callback){
const collection = db.collection('user');
collection.updateMany({sn:1},{$set:{name:'newptbird asdasasdasdd'}}).then((res)=>{
callback(res);
});
}
六、删除数据
1、删除一条数据 deleteOne
示例结果:
{ ok : 1 , n : 1}
function deleteOneDocument(db,callback){
const collection = db.collection('user');
collection.deleteOne({sn:1}).then((res)=>{
callback(res);
});
}
2、删除多条数据 deleteMany
示例结果:
{ ok : 1 , n : 3}
function deleteManyDocument(db,callback){
const collection = db.collection('user');
collection.deleteMany({sn:1}).then((res)=>{
callback(res);
});
}
文章版权:Postbird-There I am , in the world more exciting!
本文链接:http://www.ptbird.cn/nodejs-mongodb-crud.html
转载请注明文章原始出处 !