我正在尝试为webapp构建一个具有node,express和mongodb的rest api,其中我在前端有三个路由或部分
当用户单击“报价”时,他只会看到报价,“故事和新闻”也是如此。
我很困惑如何为这种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' }
]
}
]
我希望我清楚。如果您能帮助我,您会很高兴。
答案 0 :(得分:1)
我认为您走在正确的道路上,但您应该改用引用。
(1)拥有四个单独的模型和四个单独的模式是一个好主意,但我会确保将它们分为单独的文件。
(2)在您的APISchema中,您可以引用其他每个模式,如下所示:
const ApiSchema = new Schema({
quotes: [{ type: mongoose.Schema.Types.ObjectId,, ref: 'quotes' }]
stories: [{ type: mongoose.Schema.Types.ObjectId,, ref: 'stories' }],
news: [{ type: mongoose.Schema.Types.ObjectId,, ref: 'news' }]
});
(3)现在,当您创建API文档时,手边必须具有引号,故事和新闻的_id。如果这样做,从那里开始非常简单
const quotes = []; // Array of quote _ids
const stories = []; // Array of story _ids
const news = []; // Array of news _ids
const apiObject = {
quotes: quotes,
stories: stories,
news: news
};
// Save the API Object to the database
apiObject.save()
.then((savedObject) => {
// Here is your saved object. Database should be accurate.
});
这样做的好处是人口。当您从数据库中查找API文档时,可以填充这些字段中的每个字段并返回整个对象
API.find({}).populate('quotes stories news')
.then((apiObjects) => {
// Populated documents
});
另外,当您要/需要更新报价时,可以说,通过自己的模型(称为Quote.update()
而不是通过API模型尝试更新报价)来更新报价要容易得多