简体   繁体   English

Mongodb mongoose节点js架构关系

[英]Mongodb mongoose node js schema relation

hello i am new on mongodb and node js i have a question你好,我是 mongodb 和 node js 的新手,我有一个问题

here is my product schema这是我的产品架构

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const categorySchema = require('./category');

const ProductSchema = new Schema({
    country: {
        type: String,
        required: [true, "country can't be null"]
    },
    city: {
        type: String,
        default: ""
    },
    name: {
        type: String,
        required: [true, "name can't be null"]
    },
    measureValue: {
        type: Number,
        default: 0
    },
    minPrice: {
        type:Number,
        required: [true, "minPrice can't be null"],
        min: [1,"minPrice must be at least 1"]
    },
    maxPrice: {
        type:Number,
        required: [true, "maxPrice can't be null"],
        min: [1,"maxPrice must be at least 1"]
    },
    photoUrl: {
        type:String,
        default: ""
    },
    explanation: {
        type: String,
        default: ""
    },
    category: [categorySchema.schema],
    userID: {
        type: String,
        required: [true,"userid cant be null"]
    },
    isActive: {
        type: Boolean,
        default: true
    },
    createdDate: {
        type: Date,
        default: Date.now
    },
    deletedDate: {
        type:Date
    }
})

and here is my category schema这是我的类别架构

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const CategorySchema = new Schema({
 name: {
        type: String,
        required: [true, "name can't be null"]
    },
    createdDate: {
        type: Date,
        default: Date.now
    },
    deletedDate: {
        type:Date
    }
})

i need to do this;我需要这样做; every product data must be have category每个产品数据都必须有类别

if one day,one category's name changed then every product that relation with that category must changed如果有一天,一个类别的名称发生了变化,那么与该类别相关的每个产品都必须更改

i am trying to set category id to product schema and when i fetch the data it must be comes every product with category name as json我正在尝试将类别 id 设置为产品架构,当我获取数据时,它必须是每个类别名称为 json 的产品

i am really confused if you help me i'd be really thankful如果你帮助我,我真的很困惑,我真的很感激

You can set up your category as :您可以将类别设置为:

category: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'category' //your model name
    }

You can wrap it into an array and name it categories if you want multiple categories.如果需要多个类别,可以将其包装到一个数组中并命名为类别。

Then when you get the data, you will have to execute new Product().populate('category') to get retrieve the category data instead of just returning the category ObjectId.然后,当您获取数据时,您将必须执行new Product().populate('category')来检索类别数据,而不仅仅是返回类别 ObjectId。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM