简体   繁体   中英

Displaying data from a Mongodb collection in ejs using Mongoose

I am brand new to programming. I have a collection called "Practice" in my local database which has "name, role, org". I am trying to figure out how to print this info in a .ejs file using mongoose.

In my server.js, I have

require('./app/routes.js')(app, passport);     
mongoose.connect(configDB.url); // connect to our database
    var schema = mongoose.Schema;
    mongoose.model('practice', new schema({ Name: String, Role: String, Org: String}),'practice');
    var practice = mongoose.model('practice');
    practice.find({}, function(err, data) { console.log(err, data); });

In the routes,

app.get('/profileface', isLoggedIn, function(req, res) {
        res.render('profileface.ejs', {
            user : req.user
        });
    });

In the views folder, file profileface.ejs, I have the below to print the name from my "practice" collection.

<%= practice.name %>

Although it is printing in the console, when I try to access profileface.ejs, I get the following error.

ReferenceError: C:\Users\SEESCHU\Desktop\Linneus university\Assignments\302\Assignment 2\code\Test3\views\profileface.ejs:36 34| </div> 35| >> 36| <%= practice.name %> 37| 38| <!-- <div class="text-center"> 39| <p>Assignment for 4ME302</p> practice is not defined at eval (eval at <anonymous> (C:\Users\SEESCHU\Desktop\Linneus university\Assignments\302\Assignment 2\code\Test3\node_modules\ejs\lib\ejs.js:237:14), <anonymous>:30:986) at eval (eval at <anonymous> (C:\Users\SEESCHU\Desktop\Linneus university\Assignments\302\Assignment 2\code\Test3\node_modules\ejs\lib\ejs.js:237:14), <anonymous>:30:1154) at C:\Users\SEESCHU\Desktop\Linneus university\Assignments\302\Assignment 2\code\Test3\node_modules\ejs\lib\ejs.js:250:15 at Object.exports.render (C:\Users\SEESCHU\Desktop\Linneus university\Assignments\302\Assignment 2\code\Test3\node_modules\ejs\lib\ejs.js:288:13) at View.exports.renderFile [as engine] (C:\Users\SEESCHU\Desktop\Linneus university\Assignments\302\Assignment 2\code\Test3\node_modules\ejs\lib\ejs.js:318:20) at View.render (C:\Users\SEESCHU\Desktop\Linneus university\Assignments\302\Assignment 2\code\Test3\node_modules\express\lib\view.js:76:8) at Function.app.render (C:\Users\SEESCHU\Desktop\Linneus university\Assignments\302\Assignment 2\code\Test3\node_modules\express\lib\application.js:504:10) at ServerResponse.res.render (C:\Users\SEESCHU\Desktop\Linneus university\Assignments\302\Assignment 2\code\Test3\node_modules\express\lib\response.js:798:7) at C:\Users\SEESCHU\Desktop\Linneus university\Assignments\302\Assignment 2\code\Test3\app\routes.js:30:7 at callbacks (C:\Users\SEESCHU\Desktop\Linneus university\Assignments\302\Assignment 2\code\Test3\node_modules\express\lib\router\index.js:164:37) at isLoggedIn (C:\Users\SEESCHU\Desktop\Linneus university\Assignments\302\Assignment 2\code\Test3\app\routes.js:116:10) at callbacks (C:\Users\SEESCHU\Desktop\Linneus university\Assignments\302\Assignment 2\code\Test3\node_modules\express\lib\router\index.js:164:37) at param (C:\Users\SEESCHU\Desktop\Linneus university\Assignments\302\Assignment 2\code\Test3\node_modules\express\lib\router\index.js:138:11) at pass (C:\Users\SEESCHU\Desktop\Linneus university\Assignments\302\Assignment 2\code\Test3\node_modules\express\lib\router\index.js:145:5) at Router._dispatch (C:\Users\SEESCHU\Desktop\Linneus university\Assignments\302\Assignment 2\code\Test3\node_modules\express\lib\router\index.js:173:5) at Object.router (C:\Users\SEESCHU\Desktop\Linneus university\Assignments\302\Assignment 2\code\Test3\node_modules\express\lib\router\index.js:33:10)

I have spent the last 2 days trying to figure it out by googling but now I give up. I would really appreciate if you can help me.

Extra In programming, you want to keep your code organized.

Create a file eg PracticeModel.js inside app folder and move your schema logic there

var PracticeSchema = new mongoose.Schema({ 
    Name: String, 
    Role: String, 
    Org: String
});

module.exports = mongoose.model('practice', PracticeSchema, 'practice');

In your routes.js , include the newly created file at the top

var PracticeModel = require('./PracticeModel.js');

Your problem You need to (1) move the query inside your route handler and (2) pass the resultset data to the view

app.get('/profileface', isLoggedIn, function(req, res) {
    // mongoose operations are asynchronous, so you need to wait 
    PracticeModel.find({}, function(err, data) {
        // note that data is an array of objects, not a single object!
        res.render('profileface.ejs', {
            user : req.user,
            practices: data
        });
    });
});

In your view profileface.ejs , you need to iterate over the passed practices array

<% practices.forEach(function (practice) { %>
    <%= practice.Name %> <!-- note you defined the field as Name not name -->
<% }) %>

Your server.js would look like this after the changes

mongoose.connect(configDB.url);
require('./app/routes.js')(app, passport);     

Read this post on synchronous vs asynchronous . Most of the things you do in Node.js is usually asynchronous.

Hi I had the same problem, So I Did This and it worked

collection(users).find({}, (err, found) => {
 if(err){
 console.log(err)
 }else{
 res.render("Dashboard", {DataFound: found})
 }
})

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