Home > Software design >  Not able to save my array in to mongodb database
Not able to save my array in to mongodb database

Time:09-22

I am new in backend development, creating a post API by using node js and MongoDB,

This is my schema model

// restaurantSchema.js

const mongoose = require('mongoose');

const foodSchema = new mongoose.Schema({
    categoryName:{
        type: String,
        required: true
    },
    dish: [
        {
            dishName: {
                type: String,
                required: true
            },
            dishDescription: {
                type: String
            },
            dishPrice: {
                type: Number,
                required: true
            },
            // dishImg: {
            //    type: String,
            // },
            dishRating: {
                type: String
            },
        }
    ]
});

const restaurantSchema = new mongoose.Schema({
    restaurantName: {
        type: String,
       
    },
    restaurantRating:{
        type: String
    },

    restaurantAddress: {
        type: String
    },
    category: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'foodSchema'
        }
    ]
})

const Restaurant = new mongoose.model('RESTAURANT', restaurantSchema);

module.exports = Restaurant;

here is the router code

// auth.js


const express = require('express');
const router = express.Router();
require('../db/conn');
const Restaurant = require('../model/restaurantSchema');

const app = express();

router.post('/post-food', async (req, res) => {

    try {
        

        console.log(req.body, "body")
        const restaurant = new Restaurant({
            
            restaurantName: req.body.restaurantName,
            restaurantRating: req.body.restaurantRating,
            restaurantAddress: req.body.restaurantAddress,
            category: [
               {
                categoryName: req.body.categoryName
               },
                {
                    dishName: req.body.dishName,
                    dishDescription: req.body.dishDescription,
                    dishPrice: req.body.dishPrice,
                    dishRating: req.body.dishRating
                }
            ]
        });

        await restaurant.save();
        console.log(restaurant, "save")
        res.status(201).json({ message: "food added successfully" })


    } catch (err) {
        console.log(err)
    }
})

module.exports = router;

this code is going to the app.js (main file)

I am getting only this data while I comment out the category(array) in the auth.js file otherwise not able to save any data in the database file [1]: https://i.stack.imgur.com/wKn9p.png

CodePudding user response:

First of all this is a great question with very valid code, nicely done!

So, everything is correct in your code except you should declare your foodSchema as a mongoose model as well, just like you're doing so with this one

const Restaurant = new mongoose.model('RESTAURANT', restaurantSchema);

You don't need to use new, you can just omit it. So basically next to this add the declaration for your foodSchema it should look something like this:

const Restaurant = mongoose.model('RESTAURANT', restaurantSchema);
const Food = mongoose.model('FOOD', foodSchema)

and for exporting them you could do something like this:

module.exports = {
 Restaurant: Restaurant,
 Food: Food
}

For importing any of these two in your router file you could use destructuring:

const { Restaurant } = require('../model/restaurantSchema')

I hope this helps, have a good day!

CodePudding user response:

You have declared category as a list of mongoose typeId and inserting a list of object of type foodSchema. In your schema file after declaring foodSchema, create a model using that food schema.

const Food = mongoose.model('FOOD', foodSchema)

and now in restaurant schema the category will refer ref: 'Food' mongoose expecting category as ["61407ce0b6c1fc83d896002e"] but you are providing

[{
    categoryName:{
       type: String,
       required: true
    },
    dish:[...]
}]

export both Food and Restaurant from the schema file.

module.exports = Food;

for creating restaurant first create an Food

 const food = new Food({
     categoryName: req.body.categoryName,
     dish: [ {
        dishName: req.body.dishName,
        dishDescription: req.body.dishDescription,
        dishPrice: req.body.dishPrice,
        dishRating: req.body.dishRating
      } ]
    })
 let foodInserted = await food.save();

then the foodInserted._id to the category of restaurant.

const restaurant = new Restaurant({
     restaurantName: req.body.restaurantName,
     restaurantRating: req.body.restaurantRating,
     restaurantAddress: req.body.restaurantAddress,
     category: [foodInserted._id]
});

Follow this documentation

  • Related