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]
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With