简体   繁体   中英

mongoose subdocument virtual in array

Lets say i have a comment schema. A comment can have several replies. How can i create a virtual attribute to transform each reply's created_at date like this? 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
    }
  }]
});

I have no idea how to do this with an array of objects subdocument structure.

You'll need to define your subdocument seperately:

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]
   }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM