【问题标题】:Mongoose statics is not working with async and awaitMongoose statics 不适用于 async 和 await
【发布时间】:2019-12-24 20:55:57
【问题描述】:

我有一个猫鼬模型,我在其中声明了 1 个应该返回所有功能的静态变量。

const Feature = require('./featureModel')

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const schemaOptions = {
  timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' },
};

const ModemSchema = new Schema({
  proxy_type: {
    type: String,
    default: 'None'
  },
  data_prioritization: {
    type: String,
    default: 'None'
  }
}, schemaOptions);


ModemSchema.statics.possibleProxyTypes = async function () {
  features = await Feature.find({})
  return features
}

module.exports = mongoose.model('Modem', ModemSchema);

Modem.possibleProxyTypes我这样称呼它(类方法) 但是 await 没有等待,我得到了输出 [AsyncFunction] 。不知道这里出了什么问题。

【问题讨论】:

  • 您可能忘记了括号吗? Modem.possibleProxyTypes()
  • Promise { <pending> } 这是我打电话给Modem.possibleProxyTypes() @AsafAviv 时得到的结果
  • 是的,async 函数总是返回一个承诺,即使你在被调用的函数中为它await ,你也必须在承诺上调用.then()await
  • 但是 mongoose 查询也返回 promise,这就是我添加 async 和 await 的原因。我在我的控制器中使用相同类型的代码,它在那里工作,但不是在这里@AsafAviv
  • 你实际上甚至不需要async,只需要return Feature.find({})。但在这种情况下没关系,在你的控制器中包含代码

标签: node.js mongoose async-await


【解决方案1】:

我让它像这样工作。 (如果您在问题中添加了所有相关代码,我会说问题出在哪里。)

Modem Schema:(几乎没有变化,我只添加了let特性和console.log)

ModemSchema.statics.possibleProxyTypes = async function() {
  letfeatures = await Feature.find({});
  console.log(features);
  return features;
};

我在这样的示例获取路径中尝试了这个:

const Feature = require("../models/featureModel");
const Modem = require("../models/modemModel");

router.get("/modem", async (req, res) => {
  const features = await Modem.possibleProxyTypes();
  res.send(features);
});

也许问题是你没有在这一行中使用 await:

await Modem.possibleProxyTypes()

这给我带来了这样的功能:

[
    {
        "_id": "5e0207ff4323c7545026b82a",
        "name": "Feature 1",
        "__v": 0
    },
    {
        "_id": "5e0208054323c7545026b82b",
        "name": "Feature 2",
        "__v": 0
    }
]

【讨论】:

  • 我从控制台调用Modem.possibleProxyTypes(),您的代码正在运行,但我仍然对静态方法感到困惑,我用等待异步编写了相同的东西,Mongooes 查询返回承诺,所以它应该可以工作。你正在做同样的事情调用 Modem.possibleProxyTypes() 在 async & await 函数和 Modem.possibleProxyTypes() 这也返回承诺
  • 或者我认为问题是我从节点控制台调用它,如果我在执行控制即将到来时直接在代码中调用它,那么它将起作用。我正在检查这个
猜你喜欢
  • 2020-03-26
  • 2021-05-10
  • 2018-03-24
  • 1970-01-01
  • 2021-09-11
  • 2019-10-24
  • 2018-07-10
  • 2021-06-18
  • 2019-05-30
相关资源
最近更新 更多