我对 Mongo 的插入函数中可选回调的目的感到困惑。这到底是做什么用的?
var mongo = require('mongodb').MongoClient
var url = 'mongodb://localhost:27017/learnyoumongo'; // learnyoumongo is the Database
var firstName = process.argv[2];
var lastName = process.argv[3];
var doc = {
'firstName': firstName,
'lastName': lastName
}
mongo.connect(url, function(err, db) {
if (err) throw err;
// db gives access to the database
var docs = db.collection('docs');
docs.insert(doc,function(err, data){ // What is the purpose of this callback function?
if (err) throw err;
console.log(JSON.stringify(doc));
db.close()
})
});
最佳答案
doc.insert
是异步调用。它将在操作完成之前立即返回。
如果您想在插入实际完成后执行某些操作(包括检查是否成功),则需要在回调中执行此操作(随后调用)。
请注意,您正在使用 mongo.connect
执行相同的操作:您只能从回调中开始使用连接。
这是 Javascript 编程中非常常见的模式:触发后台操作,稍后接收结果作为回调的参数。
关于node.js - Mongodb插入函数语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36853601/