使用Nodejs连接mongodb数据库的实现代码

2020-06-17 06:52:22易采站长站整理

5. 查询所有文档

添加findDocuments函数


var findDocuments = function(db,callback){
// get the documents collection
var 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);
});
};

findDocuments函数查询了所有’documents’集合中所有的文档,将此函数添加到MongoClient.connect的回调函数中


var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
// Connection URL
var url = 'mongodb://localhost:27017/myproject';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected correctly to server");
insertDocuments(db, function() {
findDocuments(db, function() {
db.close();
});
});
});

6. 使用过滤条件(query filter)查询文档

查询’a’:3的文档


var findDocuments = function(db, callback) {
// Get the documents collection
var collection = db.collection('documents');
// Find some documents
collection.find({'a': 3}).toArray(function(err, docs) {
assert.equal(err, null);
console.log("Found the following records");
console.log(docs);
callback(docs);
});
}

7. 更新文档


var updateDocument = function(db,callback){
// get the documents collection
var collection = db.collection('documents');
// update document where a is 2, set b equal to 1
collection.updateOne({a:2},{
$set:{b:1}
},function(err,result){
assert.equal(err,null);
assert.equal(1,result.result.n);
console.log("updated the document with the field a equal to 2");
callback(result);
});
};

updateDocument方法更新满足条件a为2的第一个文档,新增一个b属性,并将其设置为1。

将updateDocument方法添加到MongoClient.connect方法的回调中


MongoClient.connect(url,function(err,db){
assert.equal(null,err);
console.log("Connection successfully to server");
insertDocuments(db,function(){
updateDocument(db,function(){
db.close();
});
});
});

8. 删除文档


var removeDocument = function(db,callback){
// get the documents collection
var collection = db.collection('documents');
// remove some documents
collection.deleteOne({a:3},function(err,result){