简体   繁体   English

使用nodeJS(Express)从表单将关系数据(objectId)发布到mongoDB时面临问题

[英]Facing issue while posting relational data(objectId) to mongoDB from a Form using nodeJS(Express)

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.就像我想插入带有 categoryID 的产品一样,它可以引用类别及其详细信息。 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)这是我的表格(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 POST body im getting(ignore image its uploading) error I'm getting in storing it into DB.. i'm getting data while POST request done.这是我在将其存储到数据库中时遇到的 POST 正文(忽略其上传的图像)错误。我在 POST 请求完成时获取数据。

//post obj start
{
  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")
}
//post obj end
Cant enter  //output error, while trying productSchema.save() 

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 .在某些情况下,您应该使用mongoose.Schema.ObjectId mongoose.Schema.Types.ObjectId They're similar and co-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.您的postProduct函数也有错字。

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

can you please post your one post Object and after save it to db response what you are getting back.您能否发布您的一个帖子对象,然后将其保存到数据库响应您得到的回复。 For better ref为了更好的参考

Problem has been solved, there was an typo error.问题已解决,有错别字。 As, this can be an example to relational data handling in mongoose, here is my solution.因为,这可以是猫鼬中关系数据处理的一个例子,这是我的解决方案。

//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 product.save(); //previously I have written 'productSchema.save()' now its storing data and can relate also.;
                console.log('product saved');
              } 
              catch(err){
                console.log(err);
              } 
        
        }

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

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