Cannot read property 'dsc' of undefined. Express NodeJS - javascript

I don't know what I am doing wrong and need some help please. I keep getting the same error. I log the doc it keeps saying undefined help please been trying to fix this for 16hours straight.
my model: discussionmodel.js
var mongoose = require('mongoose');
// Discussion Schema
var DscSchema = mongoose.Schema({
dsc: String,
discussionID: String
});
// Discussion model
Dsc = mongoose.model('Discussion', DscSchema);
module.exports = Dsc;
my route: questions.js
var express = require('express');
var router = express.Router();
require('../models/discussionsmodel.js');
router.get('/:id', function(req, res, next) {
var id = req.params.id;
Dsc.findById(id, function(err, doc){
console.log("log doc " + doc);
res.render('questions.ejs', {docs: doc});
});
});
module.exports = router;
My view: questions.ejs (just a part of the f
<h1>Q&A app</h1>
<h2>Discussion: <%= docs.dsc %></h2>
<h2>Questions</h2>

Related

Express router doesn't recognize mongoose model

I'm working on a node.js app, and every time I run this code it pops up a reference error saying that Post is not defined. When I put the post route into app.js instead of submit.js, it works fine. That leads me to believe it's because submit.js doesn't "see" the model defined in app.js. I'm very new to web development, so it's probably something pretty basic that I'm missing.
app.js
var express = require('express');
var mongoose = require('mongoose');
var submitRouter = require('./routes/submit');
var app = express();
mongoose.Promise = global.Promise;
mongoose.connect("mongodb://localhost:27017/posts");
//Mongoose Schema
var postSchema = new mongoose.Schema({
username: String,
date: Date,
title: String,
link: String,
text: String,
votes: Number,
community: String
});
var Post = mongoose.model("Post", postSchema);
app.use('/submit', submitRouter);
module.exports = app;
submit.js
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
router.post('/', function(req, res, next){
var newPost = new Post(req.body);
newPost.save()
.then(item => {
res.json(newPost);
})
.catch(err => {
res.status(400).send("unable to save to database");
});
});
module.exports = router;
Post is not defined It’s because you don’t have mongoose schema defined in submit.js like you did in App.js.
You are creating an instance to Post using new Post but the Post doesn’t exist in submit.js
I would recommend you to put your schema in separate file and import it in submit.js
Create a folder called schema and inside this folder create a file name called PostSchema.js
PostSchema.js
var mongoose = require('mongoose');
//Mongoose Schema
var postSchema = new mongoose.Schema({
username: String,
date: Date,
title: String,
link: String,
text: String,
votes: Number,
community: String
});
var Post = mongoose.model("Post", postSchema);
module.exports = Post;
Import post schema in submit.js
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Post = require('./schema/PostSchema.js');
router.post('/', function(req, res, next){
var newPost = new Post(req.body);
newPost.save()
.then(item => {
res.json(newPost);
})
.catch(err => {
res.status(400).send("unable to save to database");
});
});
module.exports = router;
By the way, it’s not an issue with Express Router.

.find is not a function mongoose + nodejs + express

I am trying to do a find with mongoose, but I get this
"TypeError: Query.find is not a function"
I have this model:
// file: ./models/request.js
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var dnSchema = new Schema({
customerId: String,
uuid: String,
get_data: String,
get_scores: String
});
dnSchema.index({ customerId: 1, time: -1 });
module.exports = mongoose.model('dN', dnSchema);
And I have this controller
var mongoose = require('mongoose');
var dn = mongoose.model('dn');
(...)
var getScores = exports.getScores = function(req, res) {
var Query = new dn();
console.log(Query)
Query.find({}, function(err, example) {
res.status(200).send(example)
});
}
And this index.js
var mongoose = require('mongoose');
mongoose.connect(config.url, function(err, res) {
if(err) {
logger.error('Error connecting to Database ' + process.pid);
throw err;
}
});
var models = require('./models/request')(app, mongoose);
var controllers = require('./controller/request');
var router = express.Router();
router.route('/get_scores')
.get(controllers.getScores);
app.use(router);
var httpServer = http.createServer(app);
httpServer.listen(config.port, function (){
controllers.logIn();
});
I am trying to do a simple .find, but I can do it.
I hope your help mates!!
Thanks you!!
Try to import the Schema in your controller and use that one.
var dn = require('path to schema file');
(...)
var getScores = exports.getScores = function(req, res) {
dn.find({}, function(err, example) {
res.status(200).send(example)
});
}

Mongoose model is not returning data

I'm trying to setup a model but there is no data rendering on the page (using a handlebars view engine).
I have the following in an app.js file:
// Mongoose setup
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/nickinumbers');
And then this is the model I setup for the data I need returned this is ina nickinumbers.js file:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var NickiNumberSchema = new Schema({
number: {type: 'String', required: true},
firstName: {type: 'String'}
});
var NickiNumber = mongoose.model('Nickinumber', NickiNumberSchema);
module.exports = NickiNumber;
Finally, my index.js router file contains:
var express = require('express');
var router = express.Router();
var NickiNumber = require('../models/nickinumbers');
router.get('/', function(req, res) {
NickiNumber.find(function(err, nums) {
if (err) return console.error(err);
res.render('index', {title: 'Users', nums: nums});
});
});
module.exports = router;
I'm not seeing any errors on the server or in the console and I can't figure out why this isn't working. Any help is appreciated!
In find function first parameters is query condition then apply callback.
so you should use query condition {} to get all records or can apply your query. so should use NickiNumber.find({}, function(...
Query should be like:
var express = require('express');
var router = express.Router();
var NickiNumber = require('../models/nickinumbers');
router.get('/', function(req, res) {
NickiNumber.find({}, function(err, nums) {
if (err) return console.error(err);
res.render('index', {title: 'Users', nums: nums});
});
});
module.exports = router;

insert post data into mongoDB using Node

I am very new to node JS and mongo.
I am working on a personal website that stores a user's information in my database.
For simplicity, let's say I have the following form in jade...
form(class="inputs", action="/login", method="post")
input(type="text", name="email",class="form-control", id="emailLogin", placeholder="Queen's Email")
I already set up a database, and I was able to connect to it using the following javascript...
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/user');
var db = mongoose.connection;
db.on('error', console.error);
db.once('open', function() {
// Create your schemas and models here.
});
I want to store the input from email for every user that registers using the form above.
I am guessing I would first have to create a schema, which would probably look like this, but I'm not sure...
var Schema = mongoose.Schema;
var userSchema = new Schema({
email: String
});
//I think I have to create a model too?
And to get POST data I think I would need some code that looks like this...
app.post('/login', function(request, response){
//I am not sure what to put inside
});
My question is, can someone show me how to implement all these together so that every time a user registers with their email, it is saved in the database. It is very hard to research this, and have tried and failed many times.
EDIT
Here is my index.js file...
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'QChat' });
});
module.exports = router;
Also, here is another file in my routes directory called users.js, I'm not sure what its purpose is...
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
module.exports = router;
Here are some sample codes, hope it could help you.
var userSchema = new Schema({
email: String
});
var User = mongoose.model('User', userSchema);
app.post('/login', function(request, response){
var u = new User({
email: request.body.name
});
u.save(function(err) {
if (err)
throw err;
else
console.log('save user successfully...');
});
});
Also to parse the post url correctly, express could be used here, sample codes as below.
var bodyParser = require('body-parser')
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
user.model.js
var mongoose = require('mongoose')
, Schema = mongoose.Schema
, Q = require('q')
;
var UserSchema = mongoose.Schema({
email: String,
})
UserSchema.methods.Save = function() {
return Q.ninvoke(this, 'save');
}
var User = mongoose.model('User', UserSchema);
user.controller.js
var mongoose = require('mongoose')
, User = mongoose.model('User')
;
app.post('/create', function(request, response){
var user = new User();
user.email = request.body.email;
return user.Save().then(function(users) {
// some code if save succeed
}, function(err){
// some code if save failed
});
});

ExpressJs - dbQuery is not defined

In console, when I go to specific item id I have error(ExpressJs):
ReferenceError: dbQuery is not defined
My api.js
var express = require('express'),
Bourne = require('bourne'),
bodyParser = require('body-parser'),
db = new Bourne('data.json'),
router = express.Router();
....
.route('/contact/:id')
.get(function (req, res) {
db.findOne(req,dbQuery, function (err, data) { //problem
res.json(data);
});
})
....
module.exports = router;
dbQuery is not defined? If its coming from a form it needs to be req.body.dbQuery or req.query.dbQuery.
If set somewhere else, req.dbQuery needs to be a dot not a comma.

Categories