mongoose subdocument virtual in array

时间:2015-09-06 21:37:23

标签: node.js mongodb mongoose

让我们说我有一个评论架构。评论可以有几个回复。如何创建虚拟属性来转换每个回复的created_at日期? moment(this.replies.[currentReplyIndex].created_at).format('lll')

const Comment = new mongoose.Schema({ // sort: new to old by created_at
  body: String,
  replies: [{
    body: String,
    created_at: {
      type: Date,
      default: Date.now
    }
  }]
});

我不知道如何使用对象子文档结构数组来完成此操作。

1 个答案:

答案 0 :(得分:4)

您需要单独定义子文档:

var Reply = new mongoose.Schema({
   body: String,
   created_at: {
     type: Date,
     default: Date.now
   }
});

// Virtual must be defined before the subschema is assigned to parent schema
Reply.virtual("created_at").get(function() {
  // Parent is accessible
  // var parent = this.parent();
  return moment(this.created_at).format('lll');
});


var Comment = new mongoose.Schema({
   body: String,
   replies: {
      type: [Reply]
   }
});