简体   繁体   English

为什么我无法从Mogoose的Model.find()使用console.log输出结果?

[英]Why I can't output the result with console.log from Mogoose's Model.find()?

So I've been working on MongoDB with mongoose , and I've got the following code which will be include with var tdb = require('./db.js'); 因此,我一直在使用mongoose开发MongoDB,并且获得了以下代码,这些代码将包含在var tdb = require('./db.js');

// ./db.js
module.exports = {
    update: function(data) {
        post.findOne({slug:data.slug}, (err, res) => {
            if(err) {
                post.create(data, (err, res) => {})
            } else {
                post.updateOne({slug:data.slug}, data, (err, res) => {})
            }
        })
    },
    search: function(ftype, fval, fkey) {
        var query = {};
        if(ftype != "all") {
            query[ftype] = fval;
        }
        post.find(query).lean().exec((err, res) => {
            var keys = Object.keys(res);
            var index = keys.indexOf(fkey);
            var rdata = res[fkey];
            rdata.next = res[keys[index + 1]];
            rdata.prev = res[keys[index - 1]];
            return rdata;
        })
    }
}

(The code also have other part, but I'm focusing on search function) (代码也有其他部分,但我主要关注search功能)

Which then I try to call console.log(tdb.search("all", "none", "2")); 然后我尝试调用console.log(tdb.search("all", "none", "2")); but it output undefined . 但它输出undefined But if I add console.log(rdata) above the return line, it logs out the correct response while the code console.log(tdb.search("all", "none", "2")); 但是,如果我在返回行上方添加console.log(rdata) ,它会注销正确的响应,而代码console.log(tdb.search("all", "none", "2")); still returns undefined . 仍然返回undefined

I have no idea why. 我不知道为什么。 I've thought of one issue that likely happen is that the process order isn't correct which happened with fs and fixed with promise. 我已经想到了一个可能发生的问题,即处理顺序不正确,这与fs一起发生并由promise固定。 But I don't think it's the matter since I return the value inside the callback of post.find() , which than I'm totally stuck. 但是我不认为这是问题,因为我在post.find()的回调中返回了值,这比我完全post.find() Have no idea where other can go wrong? 不知道其他地方会出错吗?

Your search function doesn't return anything so it will be undefined by default. 您的搜索功能不会返回任何内容,因此默认情况下它将是未定义的。

Also find is async. 发现是异步的。 If you remove the callback from exec , then it should return a promise. 如果从exec删除回调,则它应返回一个promise。 You can then chain a then instead and return that promise: 然后,您可以链接一个then,然后返回该诺言:

search: function(ftype, fval, fkey) {
  var query = {};
  if (ftype != "all") {
    query[ftype] = fval;
  }

  return post
    .find(query)
    .lean()
    .exec()
    .then(res => {
      var keys = Object.keys(res);
      var index = keys.indexOf(fkey);
      var rdata = res[fkey];
      rdata.next = res[keys[index + 1]];
      rdata.prev = res[keys[index - 1]];
      return rdata;
    });
}

...and then you should be able to log the result when the promise resolves using then : ...然后当promise解决时,您应该能够使用then记录结果:

tdb
  .search("all", "none", "2")
  .then(data => console.log(data));

Another way you could do this is to pass a callback function to the search function, and then invoke it with the data when ready: 您可以执行此操作的另一种方法是将回调函数传递给搜索函数,然后在准备好数据时调用它:

search: function(ftype, fval, fkey, callback) {
  var query = {};
  if (ftype != "all") {
    query[ftype] = fval;
  }

  post.find(query).lean().exec((err, res) => {
    var keys = Object.keys(res);
    var index = keys.indexOf(fkey);
    var rdata = res[fkey];
    rdata.next = res[keys[index + 1]];
    rdata.prev = res[keys[index - 1]];

    callback(rdata);
  });
}

...and then you should be able to log the result from your callback function: ...然后您应该能够记录您的回调函数的结果:

tdb.search("all", "none", "2", (data) => {
  console.log(data);
});

I hope this helps. 我希望这有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么 Json 的 Stringify output 打印与 console.log output 不同? - Why does Json's Stringify output print differently from console.log output? 如何让 console.log 输出 getter 结果而不是字符串“[Getter/Setter]”? - How can I get console.log to output the getter result instead of the string "[Getter/Setter]"? 如何查看node / express的console.log / stdout或console.error / stderr输出? - How can I view console.log/stdout or console.error/stderr output from node/express? 为什么在console.log()中看不到socket.io的服务器代码? - Why can't I see in console.log() the server code of socket.io? 使用动态模型从猫鼬查询结果 - Querying result from mongoose using dynamic model.find 猫鼬-无法在findOneAndUpdate钩子中调用model.find() - Mongoose - can't call model.find() in post findOneAndUpdate hook 我似乎无法弄清楚为什么我在 console.log 在 async/await function - I can't seem to figure out why I get 'undefined' after I console.log a value after an async/await function 节点的console.log()输出对象的信息。 如何将其输出到文件? - Node's console.log() outputs an object's info. How do I output it to a file? 我从model.find()的返回函数中得到了未定义 - I got undefined from return function from model.find() 如何使用 model.find()、Mongoose 中的 var - how can I use var out of model.find(), Mongoose
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM