Home > Net >  Facing issue while posting relational data(objectId) to mongoDB from a Form using nodeJS(Express)
Facing issue while posting relational data(objectId) to mongoDB from a Form using nodeJS(Express)

Time:07-19

Like using a schema of category and product. Products one field ref. to category schema. Like I want to insert products with categoryID so it ref category and its details. But it is not storing it to the database.

//this is category Schema

const categorySchema = new mongoose.Schema({
    catName:{type: String, unique: true, required: true},
    catDesc:{type: String, required: true}
},{timestamps:true});
//This is product Schema:

const {catSchema } = require('../models/category');
const productSchema = new mongoose.Schema({
    pname : {type: String, required: true},
    p_cat: {type: mongoose.Schema.Types.ObjectId, ref: 'category'},
    pimg : {type: String, required: true}

})
const proSchema = mongoose.model('Product', productSchema);
module.exports = proSchema

controller:

 //get req to form
        async index(req,res){
            try{
                const cat = await catSchema.find();
                console.log(cat)
                res.render('product',{category: cat});     //sending categories to view.

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

After post request i get those data. But cant store them inside database, it just throws error.

//post request to store data.

async postProduct(req,res){
            const product = new productSchema({
                pname: req.body.productName,
                p_cat: req.body.categori,    //this should get the selected category ObjId 
                pimg: req.file.filename   
            });
        
              try{
              
                const saveproduct = await productSchema.save();
                console.log('product saved');
              } 
              catch(err){
                console.log('Error encountered.');
              } 
        
        }

This is my form (ejs)

<form action="" method="post" enctype="multipart/form-data">
    <!-- upload of a single file -->
    <p>

        <input type="text" name="productName" />
    </p>
    <p>
        <label for="cat">Choose category:</label>
        <select id="category" name="categori">
            <% category.forEach((row,index)=> { %>
                <option value="<%= row._id%>">><%=row.catName %>
                </option>
                <% }) %>
        </select>
    </p>
    <p>
        <label>product img: </label>
        <input type="file" name="proimg" />
    </p>
    <p>
        <input type="submit" />
    </p>
</form>

This is the req body im getting(ignore image its uploading) error I'm getting in storing it into DB..

{
  pname: 'S21 /8GB',
  p_cat: new ObjectId("62b175373c2ed54905058f0d"), //this is the objectId coming from FORM(initially came from DB to view)

  pimg: 'proimg_1658242996770_download.jpg',
  _id: new ObjectId("62d6c7b4fd2060cc9e9c51af")
}
Cant enter

CodePudding user response:

What version of mongoose are you running? There are a few cases where instead of using mongoose.Schema.Types.ObjectId you should use mongoose.Schema.ObjectId. They're similar and exist for backwards compatibility.

const productSchema = new mongoose.Schema({
    pname : { type: String, required: true },
    // try changing the line below
    p_cat: { type: mongoose.Schema.ObjectId, ref: 'category' },
    pimg : { type: String, required: true }
})

There's also a typo on your postProduct function.

 pname: req.body.productName,
 p_cat: req.body.categori, // shouldn't be 'req.body.category'? 
 pimg: req.file.filename  

I'd generally advise to name your schema's properties more consistently.

Instead of pname I'd use name, instead of p_cat I'd use category or category_id, so that I can access them more intuitively without thinking if it's product.pname or product.cname, etc.

I also prefer to explicitly name collections, as in:

const productSchema = new mongoose.Schema({
    pname : { type: String, required: true },
    p_cat: { type: mongoose.Schema.ObjectId, ref: 'category' },
    pimg : { type: String, required: true }
// added the line below
}, { timestamps: true, collection: 'products' })

By convention, mongoose will pluralize the name passed to mongoose.model('Product', productSchema) so the collection will be named products automatically (which in most cases is fine, but could lead to wrong assumptions/naming).

Let me know if that solves your issue.

CodePudding user response:

can you please post your one post Object and after save it to db response what you are getting back. For better ref

  • Related