猫鼬架构虚拟和异步等待

时间:2019-08-05 10:29:02

标签: node.js express mongoose async-await

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

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时不等待执行。

在这方面的任何帮助将大有帮助,并受到赞赏。

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

我将 // enables Sass/SCSS support .enableSassLoader() .copyFiles({ from: './assets/images', // optional target path, relative to the output dir //to: 'images/[path][name].[ext]', // if versioning is enabled, add the file hash too //to: 'images/[path][name].[hash:8].[ext]' to: 'images/[path][name].[hash:8].[ext]' // only copy files matching this pattern //pattern: /\.(png|jpg|jpeg)$/ }).enableHandlebarsLoader(); module.exports = Encore.getWebpackConfig(); 定义为:

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; 的情况下调用异步函数,我会很高兴的。