猫鼬静态不适用于异步和等待

时间:2019-12-24 11:29:31

标签: node.js mongoose async-await

我有一个猫鼬模型,在其中声明了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我这样称呼它(类方法) 但是,等待不是等待,我得到了输出[AsyncFunction]。不知道这里出了什么问题。

1 个答案:

答案 0 :(得分:1)

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

调制解调器架构:(几乎没有变化,我只添加了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
    }
]
相关问题