mongodb 怎么建立文章分类

浏览:59日期:2023-07-03

问题描述

想弄个简单的文章发布系统,所有文章需要属于一个分类,求教数据库怎么设计,一级就够。新手刚学数据库这块。。

//文章模型var mongoose = require(’mongoose’);var Schema = mongoose.Schema;var AticleSchema = new Schema({ title: { type: String }, author_id: { type: String}, content:{type:String}, create_at: { type: Date, default: Date.now }, update_at: { type: Date, default: Date.now },});AticleSchema.index({title: 1}, {unique: true});mongoose.model(’Aticle’, AticleSchema);

问题解答

回答1:

最简单粗暴的办法,你可以通过表关联,建立两个schema,一个文章,一个文章分类。1,分类文档的schema

var mongoose = require(’mongoose’);var Schema = mongoose.Schema;var ObjectId = Schema.Types.ObjectId; // 这个是关联的地方var AticleCategorySchema = new Schema({ name: String, // 分类名字 aticle:[{type:ObjectId,ref:’Aticle’}] // 表关联})

2,另外一个文章文档的schema跟你自己写的一样,只是做一点修改

var mongoose = require(’mongoose’);var Schema = mongoose.Schema;var ObjectId = Schema.Types.ObjectId; // 这个是关联的地方var AticleSchema = new Schema({ title: { type: String }, author_id: { type: String}, content:{type:String}, create_at: { type: Date, default: Date.now }, update_at: { type: Date, default: Date.now }, aticleCategory:{ // 关联表type:ObjectId,ref:’AticleCategory’ },});

其余的代码按你的方式自行添加。

回答2:

多及分类怎么搞,怎么搞

相关文章: