nodejs连接mongodb问题
本文介绍了nodejs连接mongodb问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
按照文档创建了项目和app.js文件
文档:https://mongodb.github.io/nod...
然后在app.js中测试下面的代码:
//连接mongodb:
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 successfully to server");
db.close();
});
上面代码运行没有问题,可以打印出Connected successfully to server
。
接下来插入一个document:
var insertDocuments = function(db, callback) {
// Get the documents collection
var 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);
});
}
问题:
上面的第二段代码,也就是插入doucument,应该写在哪里?是写在第一段代码的回调函数中吗?测试了一下没反应。请各位大佬说一说。
解决方案
因为insertDocuments
是一个函数,写在回调函数之外也可以。不过,调用的时候需要放在MongoClient.connect()
的回调函数里,因为你需要刚开的链接:
// Use connect method to connect to the server
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected successfully to server");
insertDocuments(db, function() {
db.close();
});
});
insertDocuments
跑完后才可以关掉MongoDB的链接。
这篇关于nodejs连接mongodb问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文