tsm*_*tsm 4 mongoose mongodb node.js
可以说我有一个注释架构。评论可以有多个回复。我如何创建一个虚拟属性来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
}
}]
});
Run Code Online (Sandbox Code Playgroud)
我不知道如何使用对象子文档结构数组来执行此操作。
您需要分别定义子文档:
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]
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1493 次 |
| 最近记录: |