您的位置:首页 > 数据库 > Mongodb

NodeJS中MongoDB驱动mongodb使用简介

2016-05-17 19:01 691 查看
转自于:http://www.open-open.com/lib/view/open1447489698991.html

虽然说在NodeJS下连接MongoDB用Mongoose的较多,但作为其基础的mongodb库了解一下还是很有必要的。

mongodb库在npmjs的主页:
mongodb

安装

一如既往的通过npm安装,命令npm install mongodb

连接数据库

通过MongoClient.connect连接数据库,在回调中会返回db对象以供之后使用。

var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/dbname';
MongoClient.connect(url, function(err, db) {
if(err){
console.error(err);
return;
}else{
console.log("Connected correctly to server");
db.close();
}
});

获得Collection

调用db对象的collection获得collection

var collection = db.collection('collectionName');

添加记录

调用collection的insert|insertMany方法添加记录。

collection.insert[|insertMangy]({name:"myName",age:"myAge"},function(err,result){
if(err){
console.error(err);
}else{
console.log("insert result:");
console.log(result);
}
})

更新记录

调用collection的updateOne方法更新单个记录。

collection.updateOne({ a : 2 }, { $set: { b : 1 } }, function(err, result) {
if(err){
console.error(err);
}else{
console.log("update result:");
console.log(result);
}
});

删除记录

调用collection的deleteOne方法更新单个记录。

collection.deleteOne({ a : 3 }, function(err, result) {
if(err){
console.error(err);
}else{
console.log("delete result:");
console.log(result);
}
});

查询记录

调用collection的find方法查找记录,find方法的参数为查找条件。

collection.find({}).toArray(function(err, docs) {
if(err){
console.error(err);
}else{
console.log("find result:");
console.log(result);
}
});

仅仅写了基础的CRUD,详情参考 http://mongodb.github.io/node-mongodb-native/2.0
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  mongodb nodejs