【发布时间】:2022-08-08 20:54:14
【问题描述】:
我将从这个开始,因为我是后端新手,我一直在为我的问题寻找一些解决方案,但我不知道哪种解决方案适合我的问题。 所以说重点。我正在使用 Mongoose 和简单的 api 在 Next.js 中创建一个披萨餐厅项目。例如,我有集合:产品(这将是我的比萨饼),该模型的代码如下。
import mongoose from \"mongoose\";
const ProductSchema = new mongoose.Schema
{
title: {
type: String,
required: true,
maxlength: 60,
},
desc: {
type: String,
required: false,
maxlength: 200,
},
img: {
type: String,
required: false,
},
prices: {
type: [Number],
required: true,
},
extraOptions: {
type: [
{
text: { type: String, required: true },
price: { type: Number, required: true },
},
],
},},); export default mongoose.models.Product || mongoose.model(\"Product\", ProductSchema);
在这个模式中,我有一系列额外选项(例如 1 美元的额外奶酪和 1 美元的额外洋葱),但我想采用所有产品都可以具有相同附加添加剂的原则。很遗憾为每种产品(每个比萨饼)开出相同的添加剂 那么,我可以为比萨创建一个新的 extraOptions 模型并为集合产品创建一些“参考”(如在 SQL 中但在 Mongo 中)吗?例如我的 extraOptions 简单模型:
import mongoose from \"mongoose\";
const extraSchema = new mongoose.Schema(
{
title: {
type: String,
required: true,
maxlength: 60,
},
price: {
type: Number,
required: true,
},
},
);
export default mongoose.models.ExtraOptions || mongoose.model(\"ExtraOptions\", extraSchema);
我如何在产品集合中创建一个可能的参考来显示其他额外选项的所有文档?我正在阅读有关 CopyTo 方法、填充方法和子文档的信息,但我不知道哪个是我的解决方案以及如何使用它...感谢所有答案,如果我在这里写了史诗,我很抱歉。
也许有些 extraOptions: [{type:mongoose.Schema.Types.ObjectId,ref:\'extraSchema\'}],或者我真的不知道。非常感谢您的帮助
标签: node.js mongodb mongoose next.js mongoose-schema