I can’t connect Mongodb to Node

Asked

Viewed 319 times

0

I’m trying to make a page on which will have a written form Nome and Comentário, when the person fills in the name and the comment will appear under the form. Only that is giving error.

Down here is my file EJS and Just below the server file along with Mongo and the routes:

    <!DOCTYPE html>
    <html>
    <head>
        <title>X-Sports</title>
        <meta charset="utf-8">
        <link rel="stylesheet" type="text/css" href="/css/quemsomoss.css">
    </head>
    <body>
    <nav id="men">
            <ul>
                <li><picture><img class="pho" src="http://i.imgur.com/rjtgdhD.png"></picture></li>
                <li><a href="/Paginajava">Home</a></li>
                <li><a href="/quemsomos">Quem somos?</a></li>
                <li><a href="/Produtos">Produtos</a></li>
                <li><a href="/faleconosco">Fale Conosco</a></li>
                <li><form>
        <input type="search" placeholder="Buscar">
    </form></li>
            </ul>
    </nav>
    <section>
    <br>
    <br>
    <br>
    <div class="tab">
    <h1>Comentários</h1>
    <form action="/quemsomos" method ='post'>
        Nome:<input type:"text" name="Nome">
        Comentarios:<input type='text' name="Coment"><br>
        <input type="submit" value="Cadastrar">
    </form>

    <table>
        <% for(var i=0; i<resultado.length; i++){ %>
        <tr>
            <td><%= resultado[i].Nome %></td>
            <td><%= resultado[i].Comentarios %></td>
        </tr>
        <%}%>
         
    </table>
    </div>
    </section>


    </body>



    </html>

And here’s the one on my server ,

var http = require('http');
var express = require("express");
require("ejs");
var bodyparser = require('body-parser');
var mongoose = require("mongoose");

var app = express();


var Post = mongoose.Schema({
    Nome: "String",
    Comentários: "String",
});

var Coment = mongoose.model('Coment', Post);

var mongo = mongoose.connect('mongodb://localhost/Comentarios');

app.use(express.static('./public'));
app.use(express.static('./app/views'));
app.set('views' , './app/views');
app.set('view engine','ejs');
app.use(bodyparser());


app.get('/', function(req, res) {
    res.render('Paginajava');

    });
app.get('/Paginajava', function(req, res) {
     res.render('Paginajava');

    });

app.get('/quemsomos', function(req, res) {
        res.render('quemsomos');
    });

app.post('/quemsomos', function(req,res){
     var novoPost = new Coment(
        {   Nome: req.body.Nome,
            comentarios:req.body.comentarios,
        }
    );

    novoPost.save();
    resp.render("quemsomos");
    resp.end();
});

app.get("/quemsomos", function(req, resp){
    Coment.find(function(err, resultado){
        resp.render("quemsomos", { resultado: resultado} );
        resp.end();
    });

});

app.get('/produtos', function(req, res) {
    res.render('Produtos');

            
        
    });

app.get('/faleconosco', function(req, res) {
        res.render('faleconosco');
    });

var meuServidor=http.createServer(app);
meuServidor.listen(8080);

console.log("Servidor Rodando" );

2 answers

0


There are some problems with your code, I tried to solve the ones that generate errors... ;)

You are statically serving the folder /app/views, which should in principle be used only by engine (commented on that passage):

// app.use(express.static('./app/views'));

Just below you have a app.get page quemsomos, that is preventing the second app.get below render (also commented this excerpt):

/*
app.get('/quemsomos', function(req, res) {
        res.render('quemsomos');
    });
*/

In his app.post, you are setting in function res, and trying to call resp - but all right, remove the two lines, and replace with res.redirect('/quemsomos');:

app.post('/quemsomos', function(req,res){
     var novoPost = new Coment(
        {
            Nome: req.body.Nome,
            comentarios:req.body.comentarios,
        }
    );
    novoPost.save();
    res.redirect('/quemsomos');
    // res.render("quemsomos"); // removido
    // res.end(); // removido
});

Your schema are using Nome and Comentários as key - and in your app.post, is comentarios, without accent and with lowercase letter. Remove the accent, and leave the two with uppercase letter, to be as Nome. Moreover, in the view, you are using Coment and not comentarios - I changed in the server not to touch the view, but I suggest the opposite.

var novoPost = new Coment(
    {   
        Nome: req.body.Nome,
        Comentarios: req.body.Coment, // <- é Coment na view
    }
);

Remove the seat here:

var Post = mongoose.Schema({
    Nome: "String",
    Comentarios: "String", // <- estava com acento
});

Follow the changed code below - but all pages that were not part of the interaction with DB have been removed - you better follow the above step by step. The idea is that it works without having to touch the view (for testing):

var http = require('http');
var express = require("express");
require("ejs");
var bodyparser = require('body-parser');
var mongoose = require("mongoose");
var app = express();

var Post = mongoose.Schema({
    Nome: "String",
    Comentarios: "String",
});

var Coment = mongoose.model('Coment', Post);
var mongo = mongoose.connect('mongodb://localhost/Comentarios');

app.use(express.static('./public'));
app.set('views' , './app/views');
app.set('view engine','ejs');
app.use(bodyparser());

app.post('/quemsomos', function(req,res){
     var novoPost = new Coment(
        {   Nome: req.body.Nome,
            Comentarios: req.body.Coment,
        }
    );
    novoPost.save();
    res.redirect('/quemsomos');
});

app.get("/quemsomos", function(req, resp){
    Coment.find(function(err, resultado){
        resp.render("quemsomos", { resultado: resultado} );
        resp.end();
    });
});

var meuServidor=http.createServer(app);
meuServidor.listen(8080);
console.log("Servidor Rodando" );

Posts working:

site funcionando com posts

  • Thanks bro , unfortunately I could not complete the work , but I will study my mistakes for proof , Thank you

0

I fall a part of the code, since it did not pass the error. You created a schema?

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var commentSchema = new Schema({
  Nome: { String, , required: true }
  comentarios: { type: String, required: true}
});

In the link below shows an example of how to do. https://scotch.io/tutorials/using-mongoosejs-in-node-js-and-mongodb-applications Tell me if it worked. abs

  • I changed some things , now I’m making registration to appear and another page only that ta talking Usuarios is not defined.

  • which is the variable I’m using to display the information ,

  • Caio you have the project on github ? and have can I help

  • I don’t even have , I don’t know how to use git hub yet , I’m seeing if I can learn kk

  • Arthur gives a look here https://answall.com/questions/208106/nodejs-ejs-usuarios-is-not-defined-urgent

Browser other questions tagged

You are not signed in. Login or sign up in order to post.