Node.js Mongoose statics无法使用async和Wait
我有一个mongoose模型,我在其中声明了1个statics,它应该返回我所有的特性Node.js Mongoose statics无法使用async和Wait,node.js,mongoose,async-await,Node.js,Mongoose,Async Await,我有一个mongoose模型,我在其中声明了1个statics,它应该返回我所有的特性 const Feature = require('./featureModel') const mongoose = require('mongoose'); const Schema = mongoose.Schema; const schemaOptions = { timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' }, }
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
我这样调用它(类方法)
但是wait并不是在等待,我得到的是输出
[AsyncFunction]
。不确定这里出了什么问题。我让它像这样工作。(如果你在问题中添加了所有相关代码,我会说问题出在哪里。)
调制解调器模式:(几乎没有变化,我只添加了let功能和console.log)
ModemSchema.statics.possibleProxy类型=异步函数(){
letfeatures=wait Feature.find({});
console.log(特性);
返回特性;
};
我在一个示例get路线中尝试了如下:
[
{
"_id": "5e0207ff4323c7545026b82a",
"name": "Feature 1",
"__v": 0
},
{
"_id": "5e0208054323c7545026b82b",
"name": "Feature 2",
"__v": 0
}
]
const Feature=require(“../models/featureModel”);
const Modem=require(“../models/modemModel”);
路由器.get(“/modem”),异步(请求、恢复)=>{
const features=wait Modem.possibleProxy类型();
res.send(功能);
});
可能问题是您没有在这一行中使用Wait:
await Modem.possibleProxyTypes()
这为我提供了如下功能:
[
{
"_id": "5e0207ff4323c7545026b82a",
"name": "Feature 1",
"__v": 0
},
{
"_id": "5e0208054323c7545026b82b",
"name": "Feature 2",
"__v": 0
}
]
你有可能忘了括号吗
Modem.possibleProxyTypes()
Promise{}
这是我调用Modem.possibleProxyTypes()
@AsafaviYeaasync
函数时得到的结果,您必须调用。然后()
或await
在promise上,即使在调用的函数中await
,但mongoose查询也会返回promise,这就是我添加async和await的原因。我在我的控制器中使用了相同类型的代码,它在那里工作,但在这里不工作@asafaviv实际上你甚至不需要async
在这里,只需要返回特性。查找({})
。但这并不重要,在本例中,将代码包含在您的控制器中我正在从控制台调用Modem.possibleProxy()
它,您的代码正在工作,但我仍然对静态方法感到困惑,我编写了与wait和mongoos相同的东西async查询返回承诺,所以它应该工作。您在异步和等待函数中调用Modem.possibleProxyTypes()
和Modem.possibleProxyTypes()
也在做同样的事情,这也会返回Promiser,我想问题是我是从节点控制台调用它的,如果在执行控制到来时在代码中调用这个direclty,它就会工作。我正在检查这个