javascript - 使用 mongodb 函数中的字符串

标签 javascript mongodb

需要一些关于 Node js 和 mongodb 的帮助 我怎样才能返回resp?因为现在它返回“未定义”;

function(table, where, to_select) {
  var r = {};
  MongoClient.connect("mongodb://127.0.0.1:27017/db", function(err, db) {
    if(!err) {
      collection = db.collection(table);
      collection.find(where, to_select).toArray(function(err, resp) {
        r.t = resp; // return THIS
      });
    }
  });
  return r.t; //returns undefined //
}

最佳答案

由于数据库查询是异步操作,因此需要使用回调。因此,您的 return 在 find 实际返回结果之前被调用。这是修复方法

函数 runQuery(表、where、to_select、回调){ MongoClient.connect("mongodb://127.0.0.1:27017/db", 函数(err, db) { if (err) {返回回调(err);} 集合 = db.collection(表); collection.find(where,to_select).toArray(function(err, resp) { 回调(错误,响应); }); }); }

并调用您需要的函数

runQuery(table, where, select, function(err, results){
   ///do something with results.
});

希望这有帮助。

关于javascript - 使用 mongodb 函数中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39188918/

相关文章:

php - 将 js 添加到 wordpress 以实现 css activemenu 高亮显示

javascript - .html() 函数的 Jquery 替换不会尝试在 Redactor imperavi - Xss 漏洞上重写 html

mongodb - mgo 的 insert 方法是否将字段名称从大写更改为小写?

mongodb - 合并 MongoDB 中同一集合中的两个文档

c# - 如何在 MongoDb 中设置日期.月份和日期.日期

node.js - 如何将此 Mongoose 插件移植到 Mongoose 5

python - Django session

Javascript opt.prop 不是函数

javascript - Angular:JS 生成的代码的事件处理问题或无法使用 *ngfor 将类添加到 HTML 生成的代码

javascript - 如何在多数组循环中的特定位置插入项目