简体   繁体   中英

Importing data into a Mongodb schema

I am new to Node.js and 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. 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.

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.

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.

<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

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:

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. And rendering these pages separately with multiple HTTP request methods. 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 . 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; the 4th key in the 2nd schema is for the user input acquired from the 2nd page. It is a bit wordy I know. :(

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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