Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 465
aegyed Avatar asked Sep 06 '15 21:09

aegyed


1 Answers

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]
   }
});
like image 87
Jack Guy Avatar answered Nov 02 '22 13:11

Jack Guy