我正在尝试使用 Node、Express 和 MongoDB 为 Web 应用程序构建 REST API,在前端上有三个路由或部分:
我不确定如何为这种类型的 API 构建模式。这是我的方法:首先,我为每个部分单独构建模式,然后将它们全部合并到主 ApiSchema 中。我不确定这种方法是否正确。
- 名言
- 故事
- 新闻
我不确定如何为这种类型的 API 构建模式。这是我的方法:首先,我为每个部分单独构建模式,然后将它们全部合并到主 ApiSchema 中。我不确定这种方法是否正确。
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const QuotesSchema = new Schema({
author: {
type: String,
required: true
},
categories: {
type: [String],
required: true
}
})
module.exports = Quotes = mongoose.model('quotes', QuotesSchema)
const StoriesSchema = new Schema({
title: {
type: String,
required: true
},
description: {
type: String,
required: true
}
})
module.exports = Stories = mongoose.model('stories', StoriesSchema)
const NewsSchema = new Schema({
headline: {
type: String,
required: true
}
date: {
type: Date,
default: Date.now
}
})
module.exports = News = mongoose.model('news', NewsSchema)
const Quotes = require('./Quotes')
const Stories = require('./Stories')
const News = require('./News')
const ApiSchema = new Schema({
quotes: [Quotes],
Stories: [Stories],
News: [News]
})
module.exports = Api = mongoose.model('api', ApiSchema)
我希望我的 API 像以下示例一样
[
{
quotes: [
{ author: 'John', quote: 'be happy', tags: ['life', 'heart'] },
{ author: 'Mark', quote: 'be creative', tags: ['motivation', 'education'] }
]
},
{
story: [
{ title: 'broken heart', description: 'sit ae Ipsa, laboriosam!', category: ['lorem1', 'lorem2'] },
{ title: 'lorem ipsum', description: 'Lorem ipsum dolor sit.', category: ['lorem1', 'lorem2'] }
]
},
{
news: [
{ headline: 'ipsum Lorem', city: 'Jehigi' },
{ headline: 'Lorem, ipsum', city: 'Fahmori' }
]
}
]
我希望你能明确理解我的意思,如果你能帮助我就太好了。