【问题标题】:Mongoose reference in Collection for another Collection集合中的猫鼬参考另一个集合
【发布时间】: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


    【解决方案1】:

    很遗憾为每种产品开出相同的添加剂(每个 比萨)那么,我可以为比萨创建一个新的 extraOptions 模型吗? 为集合创建一些“参考”(如 SQL 但在 Mongo 中) 产品?

    您的假设是正确的 - 无需在您的每种产品中存储相同的添加剂数据。事实上,正确的方法是将添加剂数据提取到不同的集合中,并参考每种产品的相关添加剂。

    这样,您的 ProductSchema 将如下所示(为简洁起见,我排除了 'required: false' 字段,因为 false 是默认值):

    import mongoose from "mongoose";
    const ProductSchema = mongoose.Schema({
      title: {
        type: String,
        required: true,
        maxlength: 60,
      },
      desc: {
        type: String,
        maxlength: 200,
      },
      img: String,
      prices: {
        type: [Number],
        required: true,
      },
      extraOptions: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'ExtraOptions'
      }],
    });
    
    export default mongoose.models.Product || mongoose.model("Product", ProductSchema);
    

    这样,当您获取一些产品文档时,“extraOptions”属性将包含 extraOptions ducements 的 id。
    如果要检索添加剂本身的数据,而不仅仅是id,可以使用mongoose的populate方法:

    Product.find().populate('extraOptions');
    

    要进一步了解 mongoDB 中的模式设计(它可能会帮助您通常决定是引用还是嵌入),请查看this video

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-26
      • 2021-06-03
      • 2019-05-22
      • 1970-01-01
      • 2021-01-18
      • 1970-01-01
      • 2016-12-22
      • 1970-01-01
      相关资源
      最近更新 更多