gpt4 book ai didi

node.js - Mongoose 模式虚拟和异步等待

转载 作者:搜寻专家 更新时间:2023-11-01 00:47:38 25 4
gpt4 key购买 nike

我正在尝试从 mongoose 中获取一个值,并使用虚拟方法和虚拟字段将其添加到架构文档中,如下所示,

const sourceSchema = require('../source/schema.js').schema;
var Source = mongoose.model('Source', sourceSchema);

const schema = new Schema({
sourceId: {
type: Schema.Types.ObjectId,
required: true
},
description: {
type: String,
required: true
},
resources: {
type: Object
},
createdDate: {
type: Date
}
}
},
{
versionKey: false,
virtuals: true
});

schema.virtual('displayName').get(function () {
return this.getDisplayName();
});

schema.method('getDisplayName', async function () {
var source = await Source.findById(this.id);
if(source) {
var displaySource = JSON.parse(source['data']);
console.log(displaySource['displayName']);
return displaySource['displayName'];
}
});

但是在控制台中打印值时它总是空的,它从不等待执行完成。我不确定为什么在我使用 await 时它不等待执行。

对此的任何帮助都将非常有帮助,非常感谢。

最佳答案

Getters and Setters cannot be async, that's just the nature of JS.

你从未调用过回调

schema.method('getDisplayName', async function (cb) { // <-- added callback
var source = await Source.findById(this.id);
if(source) {
var displaySource = JSON.parse(source['data']);
console.log(displaySource['displayName']);
cb(displaySource['displayName']) // <-- called callback
} else cb(null)
});

然后在代码的某处

Schema.findOne(function (err, schema) {
schema.getDisplayName(function (displayName) {
// got it here
})
})

请注意,schema.virtual('displayName') 已被删除

关于node.js - Mongoose 模式虚拟和异步等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57356742/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com