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;
Related
I'm building a pretty simple API to do a basic CRUD operations on a local mongo database. The code looks fine for me but somehow the CRUD operations results on a pending request which never ends.
Here the parts of the code:
spawn.model.js (Model corresponding to database collection)
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var SpawnSchema = Schema({
Name: {
type: String,
unique: false,
required: true
}
}, { timestamps: true });
module.exports = mongoose.model('spawns', SpawnSchema);
spawn.controller.js
var Spawn = require('../models/Spawn/spawn.model');
exports.getSpawns = function(req, res){
Spawn.find({}, function(spawns){
res.send(spawns);
});
}
Here the spawn.routes.js file:
var Spawns = require('../controllers/spawn.controller');
module.exports = function(app){
app.get('/list', Spawns.getSpawns);
}
And then finally the server.js file:
var express = require('express');
var bodyParser = require('body-parser');
var properties = require('./config/properties');
var db = require('./config/database');
var app = express();
//configure bodyparser
var bodyParserJSON = bodyParser.json();
var bodyParserURLEncoded = bodyParser.urlencoded({ extended: true });
// call the database connectivity function
db();
// configure app.use()
app.use(bodyParserJSON);
app.use(bodyParserURLEncoded);
// Routes
app.get('/', function(req, res){
res.json({ message: 'Spawns API' });
});
require('./app/routes/spawn.routes')(app);
// intialise server
app.listen(properties.PORT, () => {
console.log(`Server is running on ${properties.PORT} port.`);
})
The database file on ./config is the following:
var mongoose = require('mongoose');
var dbURL = require('./properties').DB;
mongoose.Promise = global.Promise;
module.exports = function(){
mongoose.connect(dbURL, { useNewUrlParser: true }, function(){
console.log('Successfully connected to database');
});
}
And the properties.js on /config is simply an object with the database URL and the port for the express server.
When I try to to a request through Postman to the URL: http://localhost:4000/list the request gets hanged and never resolves. What am I missing?
PD: SOLVED!
===========
I needed to update mongoose version on npm cause it was 3.x and needed to be 5.x in order to work well with the new methods.
Update your code little bit, Like this and check
spwanRoute.js
const express = require('express');
const router = express.Router();
const spawnCntr = require('./speanControllers');
router.get('/list', spawnCntr.getSpawns);
module.exports = router;
spwanUtils.js
const Spawns = require('../models/Spawn/spawn.dao');
const spawnUtils = {};
spawnUtils.getSpawns = (req, res) => {
try {
Spawns.get({}, (err, spawns) => {
if(err){
return res.status(400).json({ error: err });
}
return res.status(200).json({ spawns });
});
} catch (err) {
console.log(err);
return res.status(500).json({ error: 'INTERNAL_EROR' });
}
}
module.exports = spawnUtils;
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.
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)
});
}
The express generator creates an app like this:
in the main app.js:
var app = express();
//...
var routes = require('./routes/index');
app.use('/', routes);
//...
in routes/index.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;
What is the best way to use variables that I define in app.js in the index.js?
For example, before defining the routes, I set up the mongoose model:
var myModel;
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.once('open', function (callback) {
//load schemas
var dbSchema = require('./schema');
myModel = mongoose.model('mymodel', dbSchema.myModel);
});
How can I use 'myModel' in the routes module?
You should define your models outside app.js, in their own separate files for each separate model, and export that model which you can then require in various places you need it. Your model definition doesn't actually need to be inside db.once('open'
For example: if you have a model User you should define it in its own file like this:
db/user.js
var mongoose = require('mongoose');
var schema = mongoose.Schema({
…
});
var model = mongoose.model('user', schema);
module.exports = model;
This way if you want to use the User model inside your routes/index.js:
…
var User = require('../db/user');
router.get('/user/:id', function(req, res, next) {
User.findById(req.params.id, function(err, user){
res.render('user', { title: 'Express', user: user});
});
});
Pass it as a parameter when you require your router in your app.js file. You're going to have to slightly modify your index.js file
var express = require('express');
var myRouter = function(myModel) {
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
// You can use your myModel model here
return router;
}
module.exports = myRouter
Now inside your app.js
var app = express();
//...
// Pass myModel as a parameter
var routes = require('./routes/index')(myModel);
app.use('/', routes);
//...
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>