Home > Software engineering >  How to save a document that is associated to another foreign key? in MONGODB (NO SQL)
How to save a document that is associated to another foreign key? in MONGODB (NO SQL)

Time:09-17

I would like to ask on how I can save a Sub Category by getting the ID of the Category.

Category Model

  import mongoose from 'mongoose'

const categorySchema = mongoose.Schema({
    name: {
    type: String,
    required: true,
},
})

const Category = mongoose.model('Category', categorySchema)

export default Category

Sub Category model

import mongoose from 'mongoose'

const subCategorySchema = mongoose.Schema({
    subname: {
    type: String,
    required: true,
},
categoryid: {
    type: mongoose.Schema.Types.ObjectId,
    required: true,
    ref: 'Category',
},
})

const SubCategory = mongoose.model('SubCategory', subCategorySchema)

export default SubCategory

My Controller

const createSubCategory = asyncHandler(async (req, res) => {
    const { subname, categoryid} = req.body

    const subCategoryExists = await SubCategory.findOne({
        subcategoryname,
    }).populate('categoryname')

    if (subCategoryExists) {
        res.status(400)
        throw new Error('SubCategory already exists')
    }

    const name = await Category.find({}).populate('_id')

    const subCategory = new SubCategory({
        categoryid: name,
        subcategoryname,
    })

    const createdSubCategory = await subCategory.save()

    if (createdSubCategory) {
        res.status(201).json({
            _id: createdSubCategory._id,
            categoryid: createdSubCategory,
            subname: createdSubCategory.subname,
        })
    } else {
        res.status(400)
        throw new Error('Invalid SubCategory')
    }
})

My question is

How am I going to save my Sub Category in which I will select the ID Value of the Category and insert it to the Sub Category - categoryname field ? Is is working but all I gets is the first ID in the category even if you typed another ID.

I wanted to have something like this upon saving in mongodb

SubCategory

{
    _id: 123,
    subcategory: "Sub Category",
    categoryname:{
        _id: 123456(categoryid),
        categoryname: "Categoryname"
    }
}

CodePudding user response:

I have managed to figure it out, you need to make it match. In your request.body you have your field name called categoryid so in the Category.FindOne({_id:} you need to match what you type in categoryid to the findone of _id in order for you to get that. :D

const createSubCategory = asyncHandler(async (req, res) => {
    const { subname, categoryid} = req.body

    const subCategoryExists = await SubCategory.findOne({
        subcategoryname,
    }).populate('categoryname')

    if (subCategoryExists) {
        res.status(400)
        throw new Error('SubCategory already exists')
    }

    const id= await Category.find({_id: categoryid}).populate('_id')

    const subCategory = new SubCategory({
        categoryid: id,
        subcategoryname,
    })

    const createdSubCategory = await subCategory.save()

    if (createdSubCategory) {
        res.status(201).json({
            _id: createdSubCategory._id,
            categoryid: createdSubCategory,
            subname: createdSubCategory.subname,
        })
    } else {
        res.status(400)
        throw new Error('Invalid SubCategory')
    }
})
  • Related