Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
106 views
in Technique[技术] by (71.8m points)

mongoose非主键绑定主键(表的设计)

最近在学node+数据库的一点东西,准备用express+mongodb为我的博客鲁几个简单的api

写博客评论api的时候,我设计的comment表是这样:

let commentSchema = new Schema({
 article_id: { type: Schema.Types.ObjectId, ref: "article" }
 ,reply_to: { type: String, default: null }
 ,content: { type: String, required: true }
 ,nickname: { type: String, required: true }
 ,email: { 
    type: String, 
    required: true, 
    match: /^[A-Za-z0-9._%-]+@([A-Za-z0-9-]+.)+[A-Za-z]{2,4}$/ 
 }
 ,date: { type: Date, default: Date.now }
})
module.exports = mongoose.model("comment", commentSchema);

关于reply_to(回复)我有些疑问,我想评论的回复者对应着某一条评论,(null时表示为一级评论,否者就是评论表comment的_id)

,replyTo: { type: Schema.Types.ObjectId, default: null} }

添加就会报错

ValidationError: reply_to: Cast to ObjectId failed for value "null" at path "reply_to"

大概意思就是我不能将ObjectId默认值设置为null.这里我有点困惑了,不知该如何设计,恳请同行们给点建议,谢谢~~~


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

你应该是想设计成无限级分类那样的吧,reply_to设置成关联自身模型

reply_to: {
        type: mongoose.SchemaTypes.ObjectId,
        ref: 'Comment'
},

当然可以给个默认值0,代表一级评论,说的不一定准确!~~~


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...