javascript - Can't access database from views using MongoDB NodeJS Express -
i'm having trouble accessing database 1 of 2 views created app. created app using node.js, express , mongodb data store. data stored in collection called entries key-value pairing (date: 'date', link: 'string'). in database view can access , loop through json object 'entries' after can't seem same index view despite fact wrote test console.log(entries) , when open both pages separately prints result.
when run code error: error cannot read property of undefined
i wonder if missing in how referencing them in code.
below app.js code:
var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieparser = require('cookie-parser'); var bodyparser = require('body-parser'); var router = express.router(); var moment = require('moment'); //database stuff var mongoose = require('mongoose'); var schema = mongoose.schema; //connect data store , set database var db = mongoose.connection; //connect database var conn = mongoose.connect('mongodb://localhost/mandela_diaries/data'); //create model connects schema , entries collection in mandela_diaries database var entry = mongoose.model("entry", new schema({date: 'date', link: 'string'}), "entries"); mongoose.connection.on("open", function() { console.log("mongodb connected!"); }); var routes = require('./models/index'); var users = require('./routes/users'); var database = require('./routes/database'); var methodoverride = require('method-override'); var templatemain = require('./routes/template-main'); var app = express(); // methodoverride @ top app.use(methodoverride('_method')); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); // uncomment after placing favicon in /public //app.use(favicon(__dirname + '/public/favicon.ico')); app.use(logger('dev')); app.use(bodyparser.json()); app.use(bodyparser.urlencoded({ extended: false })); app.use(cookieparser()); //serving static files app.use('/public', express.static(__dirname + '/public')); app.use('/public', express.static(__dirname + '/css')); app.use('/public', express.static(__dirname + '/js')); app.use('/public', express.static(__dirname + '/images')); app.use('/public', express.static(__dirname + '/node_modules')); app.use('/', routes); app.use('/', routes); app.use('/', routes); app.use('/database', database); app.use('/create', database); app.use('/delete', database); app.use('/:id', database); // app.use('/database/#{entry._id}?/delete', database); // catch 404 , forward error handler app.use(function(req, res, next) { var err = new error('not found'); err.status = 404; next(err); }); // error handlers // development error handler // print stacktrace if (app.get('env') === 'development') { app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } // production error handler // no stacktraces leaked user app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); module.exports = app; module.exports.entry = entry; app.listen(8080); console.log("the server has started");
my database.js code so:
var express = require('express'); var router = express.router(); var mongoose = require('mongoose'); var entry = mongoose.model('entry'); //the route getting data database - form router.get("/", function(req, res) { //send current entries page entry.find({}, function(err, entries) { console.log(entries); if(err) { res.status(404).json({"error": "not found", "err":err}); return; } else { res.render('database', {title: 'database', entries: entries}); //console.log(entries); //entries.foreach(printjson); } }); }); //the route posting data database - post router.post('/', function(req, res) { var newentry = new entry(req.body); newentry.save(function(err, entries){ if (err !== null) { res.status(500).json(err); } else { res.redirect('database'); }; }); }); //the route deleting data database - delete/remove todo item id // changed path `/` `/:id` router.delete('/:id', function (req, res) { entry.findbyid(req.params.id) .exec(function(err, entries) { // changed `if (err || !doc)` `if (err || !entries)` if (err || !entries) { res.statuscode = 404; res.send({}); } else { entries.remove(function(err) { if (err) { res.statuscode = 403; res.send(err); } else { res.send('deleted entry link: ', entries.link); } }); } }); }); module.exports = router;
my index.js code below:
var express = require('express'); var router = express.router(); var mongoose = require('mongoose'); var entry = mongoose.model('entry'); app.locals.moment = require('moment'); /* home page. */ router.get('/', function(req, res, next) { res.render('/', { title: 'express' }); entry.find({}, function(err, entries) { if(err) { res.status(404).json({"error": "not found", "err":err}); return; } else { res.render('/', {title: 'database', entries: entries}); } }); }); console.log("new code works"); module.exports = router;
my script.js code want loop through object , add elements dom:
$(document).ready(function() { //date picker jquery $(function() { $( ".datepicker" ).datepicker(); $( "#format" ).change(function() { $( ".datepicker" ).datepicker( "option", "dateformat", $( ).val() ); }); }); var browserdate = new date(); var videodate = new date(1962); //var month = browserdate.getmonth() + 1; //var day = browserdate.getdate(); var year = browserdate.getfullyear(); $.getjson('/', function() { console.log(entries); $.each(entries, function(i) { $("#context").append("on day " + context + " years ago: "); }); }); var context = year - videodate; //$('#context').append("on day " + context + " years ago:"); $('#context').html = "on day " + context + " years ago: "; console.log("on day " + context + " years ago: "); //$("body").append("hey there!"); console.log("this worked!!"); console.log(browserdate); });
then database.jade file can access entries json object somehow:
extends layout block content .container .row .col-md-12 h1 mandela diaries database .row .col-md-4 h3 add entry .row .col-md-12 form.form-inline(method='post', action='/create') .form-group label(for='date') date: input#datepicker.form-control.datepicker(type='text', name='date') .form-group label(for='link') link: input#link.form-control(type='string', name='link') button.btn.btn-default(type='submit') submit .row p | format options: br select#format option(value='mm/dd/yy') default - mm/dd/yy option(value='yy-mm-dd') iso 8601 - yy-mm-dd option(value='d m, y') short - d m, y option(value='d mm, y') medium - d mm, y option(value='dd, d mm, yy') full - dd, d mm, yy option(value="'day' d 'of' mm 'in year' yy") text - 'day' d 'of' mm 'in year' yy br ul#dbentries.col-md-12 each entry in entries p= 'date: ' + entry.date + ': link: ' + entry.link + ' ' span //- problem missing `?` `_method` parameter in query string //- `method-override` middleware check form(method='post', action='/database/#{entry._id}?_method=delete') button(type='submit') delete
and index.jade file can't access json object when try same code other still error: error cannot read property of undefined.
extends layout block content #widget.container .row #header.col-xs-12.header img#mandela_logo(src='/public/images/logo_mandeladiaries.png') .row //#context.col-xs-12 // each entry in entries // p= 'on day ' + moment(entry.date).fromnow() + ' - link: ' + entry.link + ' ' .row #videos.col-xs-12 .embed-responsive.embed-responsive-4by3 iframe(width='300', height='169', src='https://www.youtube.com/embed/4hqtamhrj8s', frameborder='0', allowfullscreen='') .row #footer.col-xs-12 img#nmf_logo(src='/public/images/logo_nmf.png') img#sabc_logo(src='/public/images/logo_sabcnews.png')
i think may simple fix that's me. appreciate help.
in index.js, calling res.render()
method twice. first time call renders view , sends rendered html string client. try remove first call , use 1 in find()
callback:
/* home page. */ router.get('/', function(req, res, next) { /* res.render('/', { title: 'express' }); <--- issue */ entry.find({}, function(err, entries) { if(err) { res.status(404).json({"error": "not found", "err":err}); return; } else { res.render('/', {title: 'database', entries: entries}); } }); });
Comments
Post a Comment