【问题标题】:Mongoose schema virual and async await猫鼬模式病毒和异步等待
【发布时间】:2019-12-12 20:49:52
【问题描述】:

我正在尝试从 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 时它不等待执行。

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

【问题讨论】:

    标签: node.js express mongoose async-await


    【解决方案1】:

    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') 已删除

    【讨论】:

      【解决方案2】:

      我将displayName定义为:

      schema.virtual("displayName").get(async function () {
        const souce = await Source.findById(this.id);
        if (source) {
          return source.displayName;
        }
        return undefined;
      });
      

      该属性在引用它之前必须有await,如下所示:

        const name = await sourceDoc.displayName;
      

      因为该属性是其他地方的异步函数。如果有人能教我如何在没有await 的情况下调用异步函数,我会非常高兴。

      【讨论】:

        猜你喜欢
        • 2018-08-30
        • 2019-05-10
        • 2018-06-11
        • 2020-10-16
        • 2016-06-22
        • 2018-04-13
        • 2019-02-15
        • 2020-08-01
        • 2018-08-09
        相关资源
        最近更新 更多