Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/41.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js Mongoose模式虚拟和异步等待_Node.js_Express_Mongoose_Async Await - Fatal编程技术网

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

Node.js Mongoose模式虚拟和异步等待,node.js,express,mongoose,async-await,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:

我正试图从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'];
  }
});
但它总是空的,尽管它在控制台中打印值,但它从不等待执行完成。我不知道为什么在我使用wait时它没有等待执行

在此方面的任何帮助都将非常有用,非常感谢。

你从没打过电话

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.virtual('displayName')
已被删除

我将
displayName
定义为:

schema.virtual("displayName").get(async function () {
  const souce = await Source.findById(this.id);
  if (source) {
    return source.displayName;
  }
  return undefined;
});
在引用属性之前,该属性必须具有
wait
,如下所示:

  const name = await sourceDoc.displayName;
因为属性在别处是异步函数。如果有人能教我如何在无需等待的情况下调用异步函数,我将非常高兴

  const name = await sourceDoc.displayName;