使用Nodejs连接mongodb数据库的实现代码
一个简单的nodejs连接mongodb示例,来自mongodb官方示例
1.创建package.json
首先,创建我们的工程目录connect-mongodb,并作为我们的当前目录
mkdirconnect-mongodb cdconnect-mongodb
输入npminit命令创建package.json
npminit
然后,安装mongodb的nodejs版本driver
npminstallmongodb--save
mongodb驱动包将会安装到当前目录下的node_modules中
2.启动MongoDB服务器
安装MongoDB并启动MongoDB数据库服务,可参考我之前的文章,或者MongoDB官方文档
3.连接MongoDB
创建一个app.js文件,并添加以下代码来连接服务器地址为192.168.0.243,mongodb端口为27017上名称为myNewDatabase的数据库
varMongoClient=require('mongodb').MongoClient,
assert=require('assert');
//ConnectionURL
varurl='mongodb://192.168.0.243:27017/myNewDatabase';
MongoClient.connect(url,function(err,db){
assert.equal(null,err);
console.log("Connectionsuccessfullytoserver");
db.close();
});
在命令行输入以下命令运行app.js
nodeapp.js
4.插入文档
在app.js中添加以下代码,使用insertMany方法添加3个文档到documents集合中
varinsertDocuments=function(db,callback){
//getthsdocumentscollection
varcollection=db.collection('documents');
//insertsomedocuments
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("Inserted3documentsintothecollection");
callback(result);
});
};
insert命令返回一个包含以下属性的对象:
- resultMongoDB返回的文档结果
- ops添加了_id字段的文档
- connection执行插入操作所使用的connection
在app.js更新以下代码调用insertDocuments方法
varMongoClient=require('mongodb').MongoClient
,assert=require('assert');
//ConnectionURL
varurl='mongodb://localhost:27017/myproject';
//Useconnectmethodtoconnecttotheserver
MongoClient.connect(url,function(err,db){
assert.equal(null,err);
console.log("Connectedsuccessfullytoserver");
insertDocuments(db,function(){
db.close();
});
});
在命令行中使用nodeapp.js运行
5.查询所有文档
添加findDocuments函数
varfindDocuments=function(db,callback){
//getthedocumentscollection
varcollection=db.collection('documents');
//findsomedocuments
collection.find({}).toArray(function(err,docs){
assert.equal(err,null);
console.log("Foundthefollowingrecords");
console.log(docs);
callback(docs);
});
};
findDocuments函数查询了所有'documents'集合中所有的文档,将此函数添加到MongoClient.connect的回调函数中
varMongoClient=require('mongodb').MongoClient
,assert=require('assert');
//ConnectionURL
varurl='mongodb://localhost:27017/myproject';
//Useconnectmethodtoconnecttotheserver
MongoClient.connect(url,function(err,db){
assert.equal(null,err);
console.log("Connectedcorrectlytoserver");
insertDocuments(db,function(){
findDocuments(db,function(){
db.close();
});
});
});
6.使用过滤条件(queryfilter)查询文档
查询'a':3的文档
varfindDocuments=function(db,callback){
//Getthedocumentscollection
varcollection=db.collection('documents');
//Findsomedocuments
collection.find({'a':3}).toArray(function(err,docs){
assert.equal(err,null);
console.log("Foundthefollowingrecords");
console.log(docs);
callback(docs);
});
}
7.更新文档
varupdateDocument=function(db,callback){
//getthedocumentscollection
varcollection=db.collection('documents');
//updatedocumentwhereais2,setbequalto1
collection.updateOne({a:2},{
$set:{b:1}
},function(err,result){
assert.equal(err,null);
assert.equal(1,result.result.n);
console.log("updatedthedocumentwiththefieldaequalto2");
callback(result);
});
};
updateDocument方法更新满足条件a为2的第一个文档,新增一个b属性,并将其设置为1。
将updateDocument方法添加到MongoClient.connect方法的回调中
MongoClient.connect(url,function(err,db){
assert.equal(null,err);
console.log("Connectionsuccessfullytoserver");
insertDocuments(db,function(){
updateDocument(db,function(){
db.close();
});
});
});
8.删除文档
varremoveDocument=function(db,callback){
//getthedocumentscollection
varcollection=db.collection('documents');
//removesomedocuments
collection.deleteOne({a:3},function(err,result){
assert.equal(err,null);
assert.equal(1,result.result.n);
console.log("removedthedocumentwiththefieldaequalto3");
callback(result);
});
};
添加到app.js中
varMongoClient=require('mongodb').MongoClient
,assert=require('assert');
//ConnectionURL
varurl='mongodb://localhost:27017/myproject';
//Useconnectmethodtoconnecttotheserver
MongoClient.connect(url,function(err,db){
assert.equal(null,err);
console.log("Connectedsuccessfullytoserver");
insertDocuments(db,function(){
updateDocument(db,function(){
removeDocument(db,function(){
db.close();
});
});
});
});
9.创建索引
索引能够改善应用的性能。下面你代码在'a'属性上添加索引
varindexCollection=function(db,callback){
db.collection('documents').createIndex({
a:1
},null,function(err,results){
console.log(results);
callback();
});
};
更新app.js
MongoClient.connect(url,function(err,db){
assert.equal(null,err);
console.log("Connectionsuccessfullytoserver");
insertDocuments(db,function(){
indexCollection(db,function(){
db.close();
});
});
});
代码已经托管在码云
总结
以上所述是小编给大家介绍的使用Nodejs连接mongodb数据库的实现代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!