Mongoose saves just '_v' and '_id' - javascript

I'm trying to add book to MongoDB and try to post with Postman it just saves _id and _v. I read a lot of answers here but neither was helpful. Get books works good but I inserted a book from command prompt.
Is there any other method to save it ?
Here is the code of api.js file:
onst express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
var Book = require('../models/book');
//MONGODB CONNECTION
mongoose.connect('mongodb://127.0.0.1:27017/books' ,({useMongoClient: true}));
mongoose.connection.on('connected', () => {
console.log('Successfully connected to MongoDB');
});
mongoose.connection.once('error', (err) =>{
console.log('Error: '+ err);
});
//Get books
router.get('/books', function(req, res) {
Book.find(function(err, books) {
if (err) {
res.send(err);
} else
res.json(books);
});
});
//Post books
router.post('/books', (req,res) => {
let newBook = new Book (req.body);
newBook.name = req.body.name,
newBook.author = req.body.author,
newBook.pages = req.body.pages,
newBook.save((err, newBook) => {
if (err){
console.log(err);
} else {
res.json(newBook);
}
});
});
module.exports = router;
Here is the code of the model file:
const mongoose = require('mongoose');
var schema = mongoose.Schema;
var bookSchema = new schema ({
name: String,
author: String,
pages: Number
});
module.exports = mongoose.model('book', bookSchema, 'books');
And code of the server file:
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const api = require('./server/routes/api');
const app = express();
//SERVER
const port = 3000;
app.listen(3000, () => {
console.log('Server started on port '+port)
});
// BODYPARSER
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
//API
app.use('/api', api);
// ROUTES
app.use(express.static(path.join(__dirname, 'dist')));
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});

Related

Getting a 502 Bad Gateway error when I try and require code from Node.js files

I am looking to start including my route files in my Node.js and express application. However, when I require the local route files into my server.js file, and try to run that on Nginx, I get a 502 Bad Gateway error.
The code that is giving me trouble is currently commented out. Any ideas on what might be causing this performance?
server.js
require('dotenv').config();
const express = require('express');
const bodyparser = require('body-parser');
const session = require('express-session');
const MongoDBStore = require('connect-mongodb-session')(session);
// const oidc = require('./okta');
// const searchRouter = require('./routes/search');
// const inputRouter = require('./routes/input');
// const dataRouter = require('./routes/view-all');
const app = express();
app.use(express.static('public'));
app.set('view engine', 'ejs');
app.get('/', function(req, res) {
res.sendFile(__dirname + '/views/index.html');
});
app.get('/page', function(req, res) {
res.render(__dirname + '/views/optishop.ejs');
});
const listener = app.listen(8080, function() {
console.log('Your app is listening on port ' + listener.address().port);
});
Edit: This is the file being required in the searchRouter declaration.
search.js
const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const oidc = require('../okta');
const router = express.Router();
router.post('/search', oidc.ensureAuthenticated(), async (req, res) => {
await MongoClient.connect(
process.env.MONGODB_URI,
{ useUnifiedTopology: true },
async (err, client) => {
assert.equal(null, err);
const db = client.db('test');
const arr = req.body.item.trim().split(/; */gi);
const user = req.session.passport.user.userinfo.sub;
const cursor = await db
.collection('test')
.find({
user
})
.toArray();
const filteredCursor = cursor.filter(obj => {
return arr.includes(obj.item);
});
res.render('index', {
cursor: filteredCursor
});
// res.send(filteredCursor);
client.close();
}
);
});
module.exports = router;

Why does save function in express not work?

This is my first day in express. I was trying to create a simple route but my save function doesn't seem to work. I tried looking at similar questions posted on stackoverflow but couldn't make it. Any help will be appreciated.
const express = require("express");
const router = express.Router();
const Post = require("../models/Post");
//ROUTES
router.post('/', (req, res) => {
const post = new Post({
title: req.body.title,
description: req.body.description
})
post.save()
.then(data => {
res.json(data);
})
.catch(err => {
res.json(err);
});
});
module.exports = router;
And here is my model.
const mongoose = require("mongoose");
const PostSchema = mongoose.Schema({
title: {
type: String,
required: true
},
description: {
type: String,
required: true
}
});
module.exports = mongoose.model('Posts',PostSchema);
app.js code
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
require("dotenv/config");
//IMPORT ROUTES
const postsRoute = require("./routes/posts");
//MIDDLEWARE - Function that always execute when routes are being hit.
app.use(bodyParser.json())
app.use('/posts', postsRoute)
//app.use('/users', usersRoute)
//ROUTES
app.get('/', (req, res) => {
res.send("We are on home");
});
//CONNECT TO DB
mongoose.connect(
process.env.DB_CONNECTION,
{ useNewUrlParser: true },
() => {
console.log("DB Connected!!")
})
//How do we start listening to the server
app.listen(3000);
My postman query -
Postman Response -
Please let me know if you need any more information.
your app.js should be :
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
require("dotenv/config");
//MIDDLEWARE - Function that always execute when routes are being hit.
app.use(bodyParser.json())
mongoose.connect(process.env.DB_CONNECTION, { useNewUrlParser: true }, function(err) {
if (err) {
console.error('System could not connect to mongo server')
console.log(err)
process.exit()
} else {
console.log('System connected to mongo server')
}
});
//ROUTES
app.get('/', (req, res) => {
res.send("We are on home");
});
//IMPORT ROUTES
const postsRoute = require("./routes/posts");
app.use('/posts', postsRoute)
app.listen(3000);
also add console log in router to check req.body :
router.post('/', (req, res) => {
console.log('req.body===',req.body);
...
});

Why does my http request not return a response

I have several routes in my api that work perfectly but while trying to implement a comment system I dont receive any response either from going to the url (node backend) or from postman.
My server JS is as follows and works for post, teams, users, but it does not work for comments.
Server.js File Below:
//load server
const express = require('express');
var cors = require('cors');
const app = express();
const morgan = require('morgan');
const mysql = require('mysql');
const bodyParser = require('body-parser');
const multer = require('multer');
//db
const db = require('./config/db');
db
.authenticate()
.then(() => {
console.log('Connection has been established successfully.');
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});
//image upload
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public')
},
filename: function (req, file, cb) {
let date = new Date(Date.now());
cb(null, date.getDay() + '-' + date.getDate() + '-' + file.originalname )
}
})
var upload = multer({ storage: storage }).single('file')
const port = process.env.PORT || 5000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}))
app.use(cors());
app.use(express.static('./public'))
app.use(morgan('combined'));
const router = require('./routes/user.js')
const postRoute = require('./routes/post.js');
app.use('/posts', require('./routes/post.js'));
app.use('/teams', require('./routes/teams.js'));
app.use('/comments', require('./routes/comments.js'));
app.use(router)
app.listen(port, () => console.log(`Listening on port ${port}`));
Below are my comment api routes:
const express =require('express');
const mysql = require('mysql');
const db = require('../config/db');
const Comments = require('../models/Comments');
// const connection = getConnection()
const router = express.Router();
const Sequelize = require('sequelize');
router.get('/', (req, res) =>
Comments.findAll().then( comments => {
console.log(comments);
res.json(comments);
// res.sendStatus(200);
})
.catch(err => console.log(err)));
router.get('/:id', (req, res) =>
Comments.findAll({
where: {
postId: req.params.id
}
}).then( comments => {
console.log(comments);
res.json(comments);
// res.sendStatus(200);
})
.catch(err => console.log(err)));
router.post('/add/:id', (req, res) => {
Comments.create(req.body).then(comments => {
console.log(req.body)
res.json(comments);
console.log(comments)
})
.catch(err => console.log(err))
});
module.exports = router;
Im posting my Teams Api Route To Show what i have that has been working perfectly for me:
//will contain all user routes
const express =require('express');
const mysql = require('mysql');
const db = require('../config/db');
const Teams = require('../models/Teams');
// const connection = getConnection()
const router = express.Router()
const Sequelize = require('sequelize');
//find all teams
router.get('/', (req, res) =>
Teams.findAll().then( team => {
console.log(team);
res.json(team);
// res.sendStatus(200);
})
.catch(err => console.log(err)));
//find Team by ID
router.get('/:id', (req, res) =>
Teams.findAll({
where: {
id: req.params.id
}
}).then( team => {
console.log(team);
res.json(team);
// res.sendStatus(200);
})
.catch(err => console.log(err)));
//add users image
module.exports = router;
It was because It was expecting a request, and i wasnt giving it one. Have to just return response.
router.get('/').then(res => {
Comments.findAll().then(comments => {
console.log(comments);
res.json(comments.data);
})
})

Not able to view JSON data

I have below code in app.js.
var express = require("express");
var app = express();
var port = 3001;
app.get("/", (req, res) => {
res.send("success");
});
app.listen(port, () => {
console.log("Server listening on port " + port);
});
var mongoose = require('mongoose');
mongoose.createConnection('mongodb://localhost:27017/mydb');
var Schema = mongoose.Schema;
var productSchema=new Schema({
created_at: String,
id: Number
});
const Products = mongoose.model("myc",productSchema);
app.get('/',function(req,res){
Products.find({},function(err,products){
res.json(products)
});
})
// module.exports = app;
I have created mongodb database mydb and myc as collection which contents the document.
When i type localhost:3000, I dont see the JSON data stored in Mongodb its shows only blank page. Please help
var express = require("express");
var app = express();
var port = 3001;
var mongoose = require('mongoose');
mongoose.createConnection('mongodb://localhost/mydb');
var Schema = mongoose.Schema;
var productSchema=new Schema({
created_at: String,
id: Number
});
const Products = mongoose.model("myc",productSchema);
app.get('/',function(req,res){
Products.find({},function(err,products){
if(!err){
res.json(products)
}
else{
res.send(err)
}
});
})
app.listen(port, () => {
console.log("Server listening on port " + port);
});
module.exports = app;

Nodejs/express - Router.use() requires middleware function but got a ' + gettype(fn));

I'm new to back-end development with node and express. i'm trying to make a back-end for a simple blog with posts and user authentication to use later in an angular 4 app.
On the "Posts" end, after testing with chrome's addon "Postman", all seems to work fine but when i started working on the "Users" side it keeps throwing off the error:
"Router.use() requires middleware function but got a ' + gettype(fn));"
When i try to run the server. The code is below:
app.js
//Imports
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const mongo = require('mongodb');
const mongoose = require('mongoose');
const passport = require('passport');
const cors = require('cors');
const config = require('./config/database');
//initialize App
var app = express();
//Setting port
var port = 3000;
//initialize cors
app.use(cors());
//Set static folder
app.use(express.static(path.join(__dirname,'../client/src')));
//initialize body parser
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
//Root route
app.get('/', function(req,res) {
res.send('Welcome to my API');
});
//Listen to port
app.listen(port, function () {
console.log('Server is running on post: ' + port);
});
//connection to DB
mongoose.connect(config.database);
mongoose.connection.on('connected', function () {
console.log('Connected to database' + config.database);
});
mongoose.connection.on('error', function (err) {
console.log('Database error' + err);
});
//Models
var Post = require('./models/post');
var User = require('./models/user');
//Routes
var postRouter = require('./routes/posts')(Post);
var userRouter = require('./routes/users')(User);
//Initialize routes
app.use('/api/posts', postRouter);
app.use('/api/users', userRouter);
models/user.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userModel = new Schema({
name: {type: String},
email: {type: String, required:true},
username: {type: String, required:true},
password: {type: String, required:true}
});
module.exports = mongoose.model('Users',userModel);
routes/users.js
var express = require('express');
var passport = require('passport');
var jwt = require('jsonwebtoken');
var userRoutes = function(User) {
var UserRouter = express.Router();
var userController = require('../controllers/userController')(User);
//Register
UserRouter.route('/register').post(userController.post);
//Authenticate
UserRouter.route('/authenticate').get();
//Profile
UserRouter.route('/profile').get();
};
module.exports = userRoutes;
controllers/userController.js
var userController = function(User) {
var post = function(req,res) {
var bcrypt = require('bcryptjs');
//creating new instance of model and pass the bodyParser
var user = new User(req.body);
if(!req.body.username) {
res.status(400);
res.send('Name is required');
}
else if (!req.body.password) {
res.status(400);
res.send('Password is required');
}
else if (!req.body.email) {
res.status(400);
res.send('Email is required');
}
else {
bcrypt.hash(user.password, function (err, hash) {
user.password = hash;
});
//saving in db
user.save();
//status 201 means created
res.status(201);
//send result
res.send(user);
}
};
return {
post: post
};
};
module.exports = userController;
The problem occurs when i initialize the users route with
app.use('/api/users', userRouter);
in app.js
"Router.use() requires middleware function but got a ' + gettype(fn));"
the error comes from this line :
app.use('/api/users', userRouter);
app.use need a path and a middleware function. Here your returning
a simple function, not a middleware, that's why you got the error.
in routes/users.js you just have to return the express.Router middleware function.
var express = require('express');
var passport = require('passport');
var jwt = require('jsonwebtoken');
var userRoutes = function(User) {
var UserRouter = express.Router();
var userController = require('../controllers/userController')(User);
//Register
UserRouter.route('/register').post(userController.post);
//Authenticate
UserRouter.route('/authenticate').get();
//Profile
UserRouter.route('/profile').get();
// UserRouter is a middleware function
return UserRouter;
};
module.exports = userRoutes;
see express router part here : http://expressjs.com/en/guide/routing.html

Categories