简体   繁体   English

将数据导入 Mongodb 模式

[英]Importing data into a Mongodb schema

I am new to Node.js and Express.js.我是 Node.js 和 Express.js 的新手。 I am working a Voting App to enhance my skills.我正在使用投票应用程序来提高我的技能。 The following is the data schema I created.以下是我创建的数据模式。

const mongoose = require('mongoose');
const register = mongoose.Schema;

const Voter = new register({ 
    firstName:{
        type:String,
        required:true,
    },

    lastName:{
        type:String,
        require:true
    },

    email:{
        type:String,
        unique:true,
        required:true
    },

    vote:{
        type:Number
    }
})

module.exports = mongoose.model('Voter',Voter)

Most of the examples/practice problems I encountered require the user to complete the data input on ONE page.我遇到的大多数示例/实践问题都需要用户在 ONE 页面上完成数据输入。 But I am thinking if there is a way to have 3 keys filled using one page, and 1 other key filled using another page.但我在想是否有办法使用一页填充 3 个键,并使用另一页填充另外 1 个键。

My preliminary design is to have the user filled in their names and email in the registration page and save them to the database, and once that is completed the user will be directed to voting page to click vote button and have that input saved to the database.我的初步设计是让用户在注册页面填写他们的姓名和电子邮件并将它们保存到数据库中,完成后用户将被引导到投票页面点击投票按钮并将该输入保存到数据库中. In total 4 entries are saved in one Schema.总共 4 个条目保存在一个 Schema 中。

I have had the registration page constructed.我已经构建了注册页面。

const express=require('express');
const router=express.Router();
const Voter = require('../models/voter');

router.get('/',(req,res)=>{
    res.render('cand/profiles')
})

router.get('/loggedin',async (req,res)=>{
    res.render('cand/index')
})

router.post('/loggedin',async (req,res)=>{
    const register = new Voter({
        firstName:req.body.first_Name,
        lastName:req.body.last_Name,
        email:req.body.email,
    })

    if (req.body.first_Name!==''||req.body.last_Name!==''||req.body.email!==''){
        var newVoter = await register.save()
        //res.send('Hello')
        res.render('cand/index',{
            voterFirstName:newVoter.firstName,
            voterLastName:newVoter.lastName,
            voterEmail:newVoter.email
        })
        console.log(newVoter)

    }else{
        res.redirect('/')
    }

})

module.exports=router

How am I supposed to deliver those filled key to the voting page ?我应该如何将那些填充的密钥传递到投票页面

Check out the example below.看看下面的例子。 The action = "/login" will redirect to login path. action = "/login"将重定向到登录路径。

<div class="form">
<form action="/login" method = "post">
  <input type="text" placeholder="E-Mail" name="email" required/>
  <input type="password" placeholder="Password" name="password" required/>
  <button>Login</button>
</form>

The js code which will be used to redirect to a specific route将用于重定向到特定路由的 js 代码

app.post('/login', passport.authenticate('login', {
    successRedirect : '/home', 
    failureRedirect : '/login', 
    failureFlash : true
}));

app.get('/home', function(request, response) {
        response.render('pages/home');
});

For displaying data from mongoose.用于显示来自猫鼬的数据。 Try the follow way.试试下面的方法。

<div id = "profile">
<h3>My Profile Info:</h3>
    <form>
        <fieldset>
            <input type = "text" value = "<%= user.user.username %>" />
       </fieldset>
    </form>

Here username is fetched from mongodb and send to html in the following way:这里用户名是从 mongodb 中获取的,并通过以下方式发送到 html:

app.get('/profile', auth, function(request, response) {
    response.render('pages/profile', {
        user : request.user
    });
})

After a hard fight, I finally came up with a solution that can solve the problem I originally raised.经过一番苦战,我终于想出了一个可以解决我最初提出的问题的解决方案。 So what I did was that having the pages for user inputs created on one routes.js file.所以我所做的是在一个 routes.js 文件上创建用户输入页面。 And rendering these pages separately with multiple HTTP request methods.并使用多种 HTTP 请求方法分别呈现这些页面。 So the pages rendered on different path will be able to let the user enter different info.因此,在不同路径上呈现的页面将能够让用户输入不同的信息。

const express=require('express');
const router=express.Router();
const Voter = require('../models/voter');
const Ballot = require('../models/ballot')

//ignore the registration for now
var newVoter=''

router.get('/',(req,res)=>{
    res.render('cand/profiles')
})

router.get('/loggedin',async (req,res)=>{
    res.render('cand/index')
})

router.post('/loggedin',async (req,res)=>{
    const register = new Voter({
        firstName:req.body.first_Name,
        lastName:req.body.last_Name,
        email:req.body.email,
    })

    if (req.body.first_Name!==''||req.body.last_Name!==''||req.body.email!==''){
        newVoter = await register.save()

        res.render('cand/index',{
            voterFirstName:newVoter.firstName,
            voterLastName:newVoter.lastName,
            voterEmail:newVoter.email
        })

    }else{
        res.redirect('/')
    }

})
router.get('/loggedin/testing',(req,res)=>{
    res.send(newBallot)
})

//testing
router.post('/loggedin/testing',async (req,res)=>{
    //res.send(newVoter)
    const ballot_info = new Ballot({
        ballotFirstName:newVoter.firstName,
        ballotLastName:newVoter.lastName,
        voteCasted:req.body.ballot
    })

    newBallot = await ballot_info.save()
    res.send(newBallot)
})

module.exports=router

But as you can see here, TWO Schemas are created .但是正如您在此处看到的,创建了两个 Schema The rationale for that is the 1st page user inputs are stored the 1st Schema.这样做的理由是第一页用户输入存储在第一架构中。 For first 3 keys in the 2nd schema, they were just filled with duplicated info from 1st Schema;对于第二个模式中的前 3 个键,它们只是填充了来自第一个模式的重复信息; the 4th key in the 2nd schema is for the user input acquired from the 2nd page.第二个模式中的第四个键用于从第二页获取的用户输入。 It is a bit wordy I know.我知道这有点罗嗦。 :( :(

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

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