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

标签 node.js express mongoose async-await

我正在尝试从 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/

相关文章:

node.js - 如何使用 docker 正确部署和扩展应用程序

javascript - 带有 collection2 的 Meteor Autoform 包不提交表单

node.js - 如何使用 llen 命令结果插入 rpush 的数据?

javascript - 使用 Mongoose findOne 的函数返回未定义?

node.js - Mongoose promise 与 bluebird 和 typescript

javascript - 用户登录时如何 'remember' -passport.js-phonegap

jquery - Node.js Express - 如何动态提供模型数据?

node.js - 使用 IIS 通过反向代理为 Node/Express API 提供服务。获取 IP 客户端 IP 地址时出现问题

node.js - Express.js sendFile 返回 ECONNABORTED

node.js - 使用 Mongoose 查找所有文件