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.
Related
i made a very simple api using express.js. Here's the code:
var express = require('express');
var app = express();
var morgan = require('morgan');
var UserModel = require('../Models/User')
app.use(morgan('short'));
app.use(express.json());
app.get('/getAll', (req, res) => {
res.status(200).json({auth: true});
})
app.post('/addUser', (req, res) => {
const { name, email, password } = req.body;
UserModel.create({name, email, password}, (err, user) => {
if(err) return res.status(500).end({auth: false})
res.status(200).end({user});
});
});
module.exports = app;
And here's the userModel:
const mongoose = require("mongoose")
const Schema = mongoose.Schema;
const UserSchema = new Schema(
{
name: String,
email: String,
password: String,
},
{timestamps: false}
);
mongoose.model("User", UserSchema);
module.exports = mongoose.model("User");
This is the main server.js file:
var express = require('express');
var app = express();
const AuthController = require("./Controllers/AuthController");
const PORT = 3001;
app.use("/api/auth", AuthController);
app.listen(PORT, () => console.log(`Listening on port ${PORT}..`))
This is the db.js file:
const mongoose = require('mongoose');
const dbRoute = "mongodb://<user>:<password>#<stuff>/nodejs-db";
mongoose.connect(
dbRoute,
{useNewUrlParser: true}
);
So here's the problem. when i try to make a request to this api using Insomnia, the requests doesn't end. Basically Insomia starts sending the request and i have to wait like 20 secs until i get something on my express terminal. If i end the request manually i get this:
::ffff:127.0.0.1 - POST /api/auth/addUser HTTP/1.1 - - - - ms
I tried looking online but couldn't find anything useful.
I come from a django backgrond. I'm new to Node and Express js.
Edit:
The problem is only with the posts requests because whenever i make a get request it returns immediately {auth: true}.
Change your .end() to .send()
app.post('/addUser', (req, res) => {
const { name, email, password } = req.body;
UserModel.create({name, email, password}, (err, user) => {
if(err) return res.status(500).send({auth: false})
res.status(200).send({user});
});
});
I solved this problem.
Apparently the problem was that my db connection was on another file.
All i did was to move the content from the db.js file to my server.js file.
I forgot to include my db file.
I'm having trouble figuring out how to save a json object from a third party api to my personal localhost mongodb. I believe I'm supposed to create another method within the api controller but am not sure what kind of method should be used any help would be great thanks!
Here is my code sorry if this is a dumb question.
//server.js
var express = require('express');
var bodyParser = require('body-parser');
var path = require('path');
var mongoose = require('mongoose');
var Router = require('./routes');
var morgan = require('morgan');
var port = process.env.PORT || 3000;
var app = express();
//database connect
mongoose.connect('mongodb://localhost/Emagispace')
app.use(
express.static('views'),
bodyParser.json(),
bodyParser.urlencoded({extended : true}),
morgan('dev')
);
Router(app);
app.listen(port, ()=>{
console.log(`Server running on ${port}`);
//Routes
var API = require('./controllers/api');
module.exports = (app)=>{
app.get('/', (req, res)=>{
res.sendFile('index.html', {root : './views'});
});
app.get('/api/emagispace', API.product)
}
//API controller
var request = require('request-promise');
var baseURI = 'example';
module.exports = {
product : (req, res)=>{
request({
method : 'GET',
url : `${baseURI}/api/emagispace/${req.query.products}`
})
.then((resp)=>{
console.log('Product list : ', resp);
res.send(resp).save();
})
}
}
In order use mongoose for saving the documents you'll need to specify the Schema first.
//product-model.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ProductSchema = new Schema({
name: String,
price: String,
//And all other data you need
});
var Product = mongoose.model('Product', ProductSchema);
Also you can do validation and much else. Please see the docs.
Then you can use .insertMany to save them in one shot or iterrate over your documents:
var Product = require('../models/product-model.js');
...
.then((resp)=>{
//I assume that resp is an array of products here
console.log('Product list : ', resp);
//Go over your product list and save them
for (var product of resp) {
var p = new Product(product);
p.save();
}
//OR
Product.insertMany(resp);
res.send(resp);
})
After this you'll have products collection in your local db.
Also you can warp these calls into a method if you want.
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;
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
});
});
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>