简体   繁体   中英

Nodejs and Mongoose

I am trying to develop a CRUD Application with the help of Node and Mongoose. Therefore I have created a contact form where the user is able to enter his email, a subject and his text. So far I am able to enter some data which is saved into my DB and also the data is shown on the same page afterwards.

Now I'm working on the Update function. I have created an additional form for the update as well where the user can put in the ID and change the data inside the DB. Now I have already created a table where the data is shown. For update I want to add another column update after each line. If the user clicks on update inside the table the data should be entered automatically inside my input field so the user just needs to change his email etc. and submit it afterwards. Till now the user has to copy the ID and then update the entry which I want to get rid off.

My files:

contact.js

var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
mongoose.connect('mongodb://admin:admin@vm-uum-docker:27000/contact_form?authSource=admin');
var Schema = mongoose.Schema;

var contactForm = new Schema({

email: {type: String, required: true},
subject: {type: String, required: true},
text: String

});

var Form = mongoose.model('Contact', contactForm);

/* GET users listing. */
router.get('/', function(req, res, next) {
//    res.render('contact');

Form.find({}, (err, entries) => {

    if (err)
        res.send(err);

    res.render('contact', {entries:entries});
});


});

router.post('/', function(req, res, next) {

var item = {

    email: req.body.email,
    subject: req.body.subject,
    text: req.body.text
}

var data = new Form(item);

function valideEmail(email){

    var re = /\S+@\S+\.\S+/;
    return re.test(email);
}

if (valideEmail(req.body.email)){

    console.log('Email is valid! Data will be saved into the DB');
    data.save();
    //res.render('contact')
    res.redirect('/contact');

} else {

    console.log('Email isn`t valid. Please try another mail!');
}

});

router.post('/update', function(req, res, next) {

var id = req.body.id;

Form.findById(id, function(err, doc) {
    if (err) {
    console.error('error, no entry found');
    }
    doc.email = req.body.email;
    doc.subject = req.body.subject;
    doc.text = req.body.text;
    doc.save();
    res.redirect('/contact');
})


});




module.exports = router;

contact.pug

doctype html
html(lang='de')
head

meta(charset='utf-8')
meta(http-equiv='X-UA-Compatible', content='IE=edge')
meta(name='viewport', content='width=device-width, initial-scale=1')




script(src='https://ajax.googleapis.com/ajax/libs/jquery
/1.11.3/jquery.min.js')

// Das neueste kompilierte und minimierte CSS
link(rel='stylesheet', href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css')
// Optionales Theme
link(rel='stylesheet', href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css')
// Das neueste kompilierte und minimierte JavaScript
script(src='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js')

link(rel='stylesheet', href='/stylesheets/style.css')

title Kontaktformular


body

.container
  h1 Get in touch!
  #message
  form(action='http://localhost:3000/contact', method='POST')
    .form-group
      label(for='email') Email address
      input#email.form-control(type='text', placeholder='Enter email', name='email')
      p.help-block We'll never share your email with anyone else.
    .form-group
      label(for='subject') Subject
      input#subject.form-control(type='text', name='subject')
    .form-group
      label(for='text') What would you like to ask us?
      textarea.form-control(rows='5', name='text')
    button#submit.btn.btn-primary(type='submit') Submit


.container
  h2 Update data
  form(action='http://localhost:3000/contact/update', method='POST')
    .form-group
      label(for='id') ID
      input#id.form-control(type='text', placeholder='Give a specific ID to update your entry in the DB', name='id')
    .form-group
      label(for='email') Email address
      input#email.form-control(type='text', placeholder='Enter email', name='email')
      p.help-block We'll never share your email with anyone else.
    .form-group
      label(for='subject') Subject
      input#subject.form-control(type='text', name='subject')
    .form-group
      label(for='text') What would you like to ask us?
      textarea.form-control(rows='5', name='text')
    button#submit.btn.btn-primary(type='submit') Submit

hr
.container
  if entries
    table.table.table-bordered
      thead
        tr
          th ID
          th Email
          th Subject
          th Text
          th Update Content
      tbody
      each entry in entries
        tr
          td #{entry._id}
          td #{entry.email}
          td #{entry.subject}
          td #{entry.text}
          td a(href='google.com') Google




script(type='text/javascript').

    document.getElementById('submit').onclick = function(e){

        function valideEmail(email){

            var re = /\S+@\S+\.\S+/;
            return re.test(email);
        }

        if (valideEmail(document.getElementById('email').value)){

            document.getElementById('message').innerHTML = '<div class="alert alert-success">Your message was sent, we`ll respond ASAP!</div';

        } else {

            document.getElementById('message').innerHTML = '<div class="alert alert-danger">Your message was`t sent, please check your entries!</div';
            e.preventDefault();

        }
    }

I would be really thankful for any kind of help

I have made basic node js crud application using mlab,mongoDB, mongoose database

const mongoose = require('mongoose');
let dev_db_url = 'mongodb://Anuj:Anuj123@ds233320.mlab.com:33320/db1';
const mongoDB = process.env.MONGODB_URI || dev_db_url;
mongoose.connect(mongoDB, { useNewUrlParser: true });
mongoose.Promise = global.Promise;
const db = mongoose.connection;
db.on('error', console.error.bind(console,'MongoDb Connection Error'));

with MVC structure - routers, models, controllers and also put post delete data Refer this - Nodejs Crud app

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