简体   繁体   中英

Mongodb mongoose node js schema relation

hello i am new on mongodb and node js i have a question

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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