如何在nodejs和express中从多步表单提交数据到MongoDB?

3

我是一个Node.js和Express的新手。

我正在尝试使用Node.js、Express和MongoDB创建一个名片生成器应用程序。

我已经在ejs中创建了一个多步骤表单,并希望将输入的数据存储在MongoDB中。 请问有人可以告诉我如何做到这一点吗?以下是我尝试使用的ejs和js代码片段。

MongoDB模式也已提供。

提前致谢。

<section class="multi_step_form">
    <form action="/blogs" method="POST" enctype="multipart/form-data" id="msform">
        <!-- Tittle -->
        <div class="tittle">
            <h2>New Card</h2>
        </div>
        <!-- progressbar -->
        <ul id="progressbar">
            <li class="active">Personal details</li>
            <li>About Section</li>
            <li>Product Section</li>
        </ul>
        <!-- fieldsets -->
        <fieldset>
            <div class="form-row align-items-center">
                <div class=" col-md-3 ">
                    <h5>Name</h5>
                </div>
                <div class="form-group col-md-9 ">
                    <input type="text " class="form-control " placeholder="Name of the Card Holder" name="name " required>
                </div>
            </div>

            <div class="form-row align-items-center">
                <div class="col-md-3 ">
                    <h5>Company</h5>
                </div>
                <div class="form-group col-md-9 ">
                    <input type="text " class="form-control" placeholder="Name of the Company" name="company">
                </div>
            </div>

            <div class="form-row align-items-center">
                <div class="col-md-3 ">
                    <h5>Designation</h5>
                </div>
                <div class="form-group col-md-9 ">
                    <input type="text " class="form-control" placeholder="Designation at the Company" name="designation">
                </div>
            </div>

            <div class="form-row align-items-center">
                <div class="col-md-3 ">
                    <h5>Phone Number</h5>
                </div>
                <div class="form-group col-md-9 ">
                    <input type="text " class="form-control" placeholder="Phone Number" name="phone_no">
                </div>
            </div>

            <div class="form-row align-items-center">
                <div class="col-md-3 ">
                    <h5>Email</h5>
                </div>
                <div class="form-group col-md-9 ">
                    <input type="text " class="form-control" placeholder="Email ID" name="email">
                </div>
            </div>
            <div class="form-row align-items-center">
                <div class="col-md-3 ">
                    <h5>Address</h5>
                </div>
                <div class="form-group col-md-9 ">
                    <input type="text " class="form-control" placeholder="Address" name="address">
                </div>
            </div>
            <div class="form-row align-items-center">
                <div class="col-md-3 ">
                    <h5>Profile Photo</h5>
                </div>

                <div class="form-group col-md-9 ">
                    <input type="file" name="image" id="image" class="form-control-file">
                </div>
            </div>
            <div class="form-group">
            </div>

            <button type="button " class="action-button previous_button ">Back</button>
            <button type="button " class="next action-button ">Continue</button>
        </fieldset>

        <fieldset>
            <div class="form-row align-items-center">
                <div class="col-md-3 ">
                    <h5>Year of Establishment</h5>
                </div>
                <div class="form-group col-md-9 ">
                    <input type="text " class="form-control" placeholder="Year of Establishment of the Company" name="year_of_establishment">
                </div>
            </div>
            <div class="form-row align-items-center">
                <div class="col-md-3 ">
                    <h5>Description</h5>
                </div>
                <div class="form-group col-md-9 ">
                    <input type="text " class="form-control" placeholder="Description about the Company" name="description">
                </div>
            </div>
            <div class="form-row align-items-center">
                <div class="col-md-3 ">
                    <h5>Profile Photo</h5>
                </div>

                <div class="form-group col-md-9 ">
                    <input type="file" name="image" id="image" class="form-control-file">
                </div>
            </div>
            <button type="button " class="action-button previous previous_button ">Back</button>
            <button type="button " class="next action-button ">Continue</button>
        </fieldset>
        <fieldset>
            <div class="form-row align-items-center">
                <div class="col-md-3 ">
                    <h5>Product 1</h5>
                </div>
                <div class="form-group col-md-9 ">
                    <input type="text " class="form-control" placeholder="Name of product" name="product">
                </div>
            </div>
            <div class="form-row align-items-center">
                <div class="col-md-3 ">
                    <h5>Description</h5>
                </div>
                <div class="form-group col-md-9 ">
                    <input type="text " class="form-control" placeholder="Description about the product" name="product_desc">
                </div>
            </div>
            <div class="form-row align-items-center">
                <div class="col-md-3 ">
                    <h5>Product Images</h5>
                </div>

                <div class="form-group col-md-9 ">
                    <input type="file" name="product_img" id="image" class="form-control-file">
                </div>
            </div>

            <button type="button " class="action-button previous previous_button ">Back</button>
            <button type="submit" class="action-button ">Save</a></button>
        </fieldset>
    </form>
</section>
<!-- End Multi step form -->


router.post('/', upload.single('image'), async(request, response) => {
    console.log(request.file);
    console.log(request.body);
    let blog = new Blog({
        name: request.body.name,
        company: request.body.company,
        designation: request.body.designation,
        phone_no: request.body.phone_no,
        address: request.body.address,
        img: request.file.filename,
        year_of_establishment: request.body.year_of_establishment,
        description: request.body.description,
        product_name: request.body.product_name,
        product_desc: request.body.product_desc,
        product_img: request.file.filename,
    });

    try {
        blog = await blog.save();
        response.redirect('blogs/editAbout');
        //response.redirect(`blogs/${blog.slug}`);
    } catch (error) {
        console.log(error);
    }
});


const blogSchema = new mongoose.Schema({ 名称: { 类型: 字符串,

},
img: {
    type: String,

},
company: {
    type: String,
    //required: true,
},
designation: {
    type: String,
},
phone_no: {
    type: String,
},
address: {
    type: String,
},
year_of_establishment: {
    type: String,
},
description: {
    type: String,
},
product_name: {
    type: String,
},
product_desc: {
    type: String,
},
product_img: {
    type: String,
},


timeCreated: {
    type: Date,
    default: () => Date.now(),
},
/*snippet: {
    type: String,
},*/

slug: { type: String, slug: 'name', unique: true, slug_padding_size: 2 },

});

2个回答

1
<html>
  <head>
    <title><%= title %></title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
    <section class="multi_step_form">
      <form action="/blogs" method="POST"  enctype="multipart/form-data" id="msform">
          <!-- Tittle -->
          <div class="tittle">
              <h2>New Card</h2>
          </div>
          <!-- progressbar -->
          <ul id="progressbar">
              <li class="active">Personal details</li>
              <li>About Section</li>
              <li>Product Section</li>
          </ul>
          <!-- fieldsets -->
          <fieldset>
              <div class="form-row align-items-center">
                  <div class=" col-md-3 ">
                      <h5>Name</h5>
                  </div>
                  <div class="form-group col-md-9 ">
                      <input type="text " class="form-control " placeholder="Name of the Card Holder" name="name " required>
                  </div>
              </div>
  
              <div class="form-row align-items-center">
                  <div class="col-md-3 ">
                      <h5>Company</h5>
                  </div>
                  <div class="form-group col-md-9 ">
                      <input type="text " class="form-control" placeholder="Name of the Company" name="company">
                  </div>
              </div>
  
              <div class="form-row align-items-center">
                  <div class="col-md-3 ">
                      <h5>Designation</h5>
                  </div>
                  <div class="form-group col-md-9 ">
                      <input type="text " class="form-control" placeholder="Designation at the Company" name="designation">
                  </div>
              </div>
  
              <div class="form-row align-items-center">
                  <div class="col-md-3 ">
                      <h5>Phone Number</h5>
                  </div>
                  <div class="form-group col-md-9 ">
                      <input type="text " class="form-control" placeholder="Phone Number" name="phone_no">
                  </div>
              </div>
  
              <div class="form-row align-items-center">
                  <div class="col-md-3 ">
                      <h5>Email</h5>
                  </div>
                  <div class="form-group col-md-9 ">
                      <input type="text " class="form-control" placeholder="Email ID" name="email">
                  </div>
              </div>
              <div class="form-row align-items-center">
                  <div class="col-md-3 ">
                      <h5>Address</h5>
                  </div>
                  <div class="form-group col-md-9 ">
                      <input type="text " class="form-control" placeholder="Address" name="address">
                  </div>
              </div>
              <div class="form-row align-items-center">
                  <div class="col-md-3 ">
                      <h5>Profile Photo</h5>
                  </div>
  
                  <div class="form-group col-md-9 ">
                      <input type="file" name="image" id="image"   class="form-control-file">
                  </div>
              </div>
              <div class="form-group">
              </div>
  
              <button type="button " class="action-button previous_button ">Back</button>
              <button type="button " class="next action-button ">Continue</button>
          </fieldset>
  
          <fieldset>
              <div class="form-row align-items-center">
                  <div class="col-md-3 ">
                      <h5>Year of Establishment</h5>
                  </div>
                  <div class="form-group col-md-9 ">
                      <input type="text " class="form-control" placeholder="Year of Establishment of the Company" name="year_of_establishment">
                  </div>
              </div>
              <div class="form-row align-items-center">
                  <div class="col-md-3 ">
                      <h5>Description</h5>
                  </div>
                  <div class="form-group col-md-9 ">
                      <input type="text " class="form-control" placeholder="Description about the Company" name="description">
                  </div>
              </div>
              <div class="form-row align-items-center">
                  <div class="col-md-3 ">
                      <h5>Profile Photo</h5>
                  </div>
  
                  <div class="form-group col-md-9 ">
                      <input type="file" name="image" id="image" multiple class="form-control-file">
                  </div>
              </div>
              <button type="button " class="action-button previous previous_button ">Back</button>
              <button type="button " class="next action-button ">Continue</button>
          </fieldset>
          <fieldset>
              <div class="form-row align-items-center">
                  <div class="col-md-3 ">
                      <h5>Product 1</h5>
                  </div>
                  <div class="form-group col-md-9 ">
                      <input type="text " class="form-control" placeholder="Name of product" name="product">
                  </div>
              </div>
              <div class="form-row align-items-center">
                  <div class="col-md-3 ">
                      <h5>Description</h5>
                  </div>
                  <div class="form-group col-md-9 ">
                      <input type="text " class="form-control" placeholder="Description about the product" name="product_desc">
                  </div>
              </div>
              <div class="form-row align-items-center">
                  <div class="col-md-3 ">
                      <h5>Product Images</h5>
                  </div>
  
                  <div class="form-group col-md-9 ">
                      <input type="file" name="image" id="image" multiple class="form-control-file">
                  </div>
              </div>
  
              <button type="button " class="action-button previous previous_button ">Back</button>
              <button type="submit" class="action-button ">Save</a></button>
          </fieldset>
      </form>
  </section>
  </body>
</html>

        
        /* Schema */
        
        var mongoose=require('mongoose');
        mongoose.connect('mongodb://localhost:27017/mydb',
        {
        useNewUrlParser: true,
        useUnifiedTopology: true,
        useCreateIndex: true,
        useFindAndModify: false
        }
        );
        
        var conn=mongoose.connection;
        
        const blogSchema = new mongoose.Schema({ 
            
            name: { type: String },
        
            company: {type: String },
        
            designation: { type: String },
        
            phone_no: { type: String },
        
            email: { type: String },
        
            address: { type: String },
        
            year_of_establishment: { type: String },
            
            description: { type: String },
        
            product_name: { type: String},
        
            product_desc: { type: String},
            
            avtar: [String],
        
            timeCreated: { type: Date, default: () => Date.now()},
            
        });
        
        var BlogSchema = mongoose.model('BlogSchema',blogSchema);
        
        module.exports=BlogSchema;
        
        /* Use Routes */
        var express = require('express');
        var router = express.Router();
        const multer = require('multer');
        const path = require('path');
        const userModal = require("../modals/userSchema")
        //router.use(express.static(__dirname+'./public/'));
        
        
        var Storage=multer.diskStorage({
          destination:"./public/images",
          filename:(req,file,cb)=>{
            cb(null,file.fieldname+"_"+Date.now()+path.extname(file.originalname));
          }
        });
        
        var upload=multer({
        storage:Storage
        }).array('image');
        
        
        /* GET users listing. */
        router.post('/blogs', upload,  async(request, response) => {
           let arr=[];
          for(let i=0;i<request.files.length;i++){
             arr[i]=request.files[i].filename;
          }
          let user = new userModal({
              name: request.body.name,
              company: request.body.company,
              designation: request.body.designation,
              phone_no: request.body.phone_no,
              email:request.body.email,
              address: request.body.address,
              year_of_establishment: request.body.year_of_establishment,
              description: request.body.description,
              product_name: request.body.product_name,
              product_desc: request.body.product_desc,
              avtar: arr,
          });
        
          try {
              blog = await user.save();
          } catch (error) {
              console.log(error);
          }
        });[![enter image description here][1]][1]
        
    https://istack.dev59.com/XHGzn.webp
            enter code here
        
        module.exports = router;
    [1]: https://istack.dev59.com/XHGzn.webp

谢谢你的回答。实际上,我想知道如何从我创建的多步表单中一次性将数据发布到MongoDB。 如果您能帮助我解决这个问题,我将不胜感激。 - Vishnu Sastry H K
尝试这段代码并请标记最佳答案。 - Sumit Pathak

0

默认情况下,NodeJS / Express不会将多部分表单数据提交给控制器。请求的主体将为空。

您可以使用Multer来处理它:

const multer = require('multer');
const upload = multer();

app.post("/legitimation/process", upload.none(), async (req, res) => {
    console.log(req.body);
    res.redirect("/legitimation/id-now");
});

查看此参考资料


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接