Mongoose find null response - node.js

I try to make a get request on /movies/{movieId} route to get a movie info and I get an empty array.
I have used findOne() function and I have the get the same empty array.
When I use as path /movies works fine and I can get all the movies that I have inside my database.
app.js
const express = require('express');
const app = express();
const mongoose = require ('mongoose');
const bodyParser = require('body-parser');
require('dotenv/config');
app.use(bodyParser.json());
//Import routes
const postsRoute = require('./routes/posts');
const moviesRoute = require('./routes/movies');
app.use('/posts', postsRoute);
app.use('/movies', moviesRoute);
//Middlewares
app.use('/posts', () =>{
console.log('This is a middleware running');
})
//ROUTES
app.get('/', (req, res) =>{
res.send('We are on home');
})
//Connect to database
mongoose.connect(
process.env.DB_CONNECTION,
{ useNewUrlParser: true }, () =>{
console.log('Connected to the database!');
})
//How to start listen from server
app.listen(3000);
route for movies
const express = require('express');
const router = express.Router();
const Movie = require('../models/Movies');
//GET BACK ALL THE MOVIES
router.get('/', async (req, res) =>{
try{
const movies = await Movie.find();
res.json(movies);
}catch(err){
res.json({message : err});
}
})
//SUBMIT A MOVIE
router.post('/', async (req, res) => {
const movie = new Movie({
movieId: req.body.movieId,
tittle: req.body.title,
genres: req.body.genres
});
try{
const savedMovie = await movie.save();
res.json(savedMovie);
}catch(err){
res.json({message: err});
}
});
//SPECIFIC MOVIE
router.get('/:movieId', async (req, res) =>{
try{
const movie = await Movie.find({ movieId: req.params.movieId }).exec();
console.log(req.params.movieId);
console.log(movie);
res.json(movie);
}catch(err){
res.json({message: err});
}
});
module.exports = router;
movies model
const mongoose = require('mongoose');
const MovieSchema = mongoose.Schema({
movieId: Number,
title: String,
genres: String
});
module.exports = mongoose.model('Movies', MovieSchema);

It's not correct to use two GET methods for one route and Express will not recognize this and it's only able to define the first GET method you written !
so, in your code as "/" and "/:movieId" are both routes for "/" , Only the first one will work.
Solution:
In your moviesRoute Use only one route and use both logics in that one:
router.get('/:movieId', async (req, res) =>{
try{
let {movieId} = req.params;
if(typeof movieId === 'undefined'){
// if user just send request to "/movies" path
const movies = await Movie.find();
res.json(movies);
}
else{
// if user asked for specific movie id like "/movies/{id}"
const movie = await Movie.find({movieId}).exec();
console.log(req.params.movieId);
console.log(movie);
res.json(movie);
}
}
catch(err){
res.json({message: err});
}
});

you should convert movieId to a number, do like this:
router.get('/:movieId', async (req, res) =>{
try{
const movie = await Movie.find({ movieId: +req.params.movieId }).exec();
console.log(req.params.movieId);
console.log(movie);
res.json(movie);
}catch(err){
res.json({message: err});
}
});

Related

0 I am working on NodeJs application it's shop application. I am trying to save posts in database and I am getting this error after submitting form:

TypeError: Post is not a constructor
owoce.js
const express = require('express');
const router = express.Router();
const Post = require('../models/owoc');
router.get('/', (req,res) => {
res.send('we are on owoce');
//try {
// const owoce = await Owoc.find()
// res.json(owoce)
// }catch (err){
// res.status(500).json({ message: err.message })
// }
})
// router.get('/jablka', (req,res) => {
// res.send('we are on jablka');
//});
router.post('/', (req,res) => {
const owoc = new Post({
rodzaj: req.body.rodzaj,
kolor: req.body.kolor
})
owoc.save()
.then(data =>{
res.json(data);
})
.catch(err => {
res.json({message: err});
});
});
module.exports = router;
owoc.js it includes schema
const mongoose = require('mongoose');
const OwocSchema = new mongoose.Schema({
rodzaj: {
type: String,
required: true
},
kolor: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
});
//mongoose.Schema({
// username: String,
// password: String
//})
mongoose.exports = mongoose.model('Owoc', OwocSchema)
I am not sure what the problem is after looking at simmilar anwseres here
i dont see what should be changed
const Post = require('../models/owoc');
server.js adding it coz it may be usefull to troubleshoot
const express = require('express')
//const req = require('express/lib/request');
//const res = require('express/lib/response');
const app = express()
const mongoose = require('mongoose')
const bodyParser = require('body-parser');
require('dotenv/config');
app.use(bodyParser.json());
//const db = mongoose.connection('mongodb://localhost/sklep')
//MIDDLEWARES
app.use('/posts', ()=> {
console.log('This is a middleware');
});
//IMPORT ROUTES
const owoceRoute = require('./routes/owoce');
app.use('/owoce', owoceRoute);
//ROUTES
app.get('/', (req,res) => {
res.send('we are on home');
});
//connect to DB
mongoose.connect(
process.env.DB_CONNECTION ,mongoose.set('strictQuery', true), ()=> {
console.log('Connected to DB!!:))');
}); //{ useNewUrlParser: true})
//how to lisen to server
///db.on('error',(error) => console.error(error))
///db.once('open',() => console.log('connected to database'))
//db.on('connected', () => console.log('Connected to database'))
app.listen(3000, () => console.log('server started'))
I am adding screenshot and server code app despite not being sure if it will be any help
here is the screen from Postman
try this:
router.post('/create', async (req,res) => {
const owoc = await Owoc.create({
rodzaj: req.body.rodzaj,
kolor: req.body.kolor
})
.then(data =>{
res.json(data);
})
.catch(err => {
res.json({message: err});
});
});

Why POST request is not getting sent?

Creating CRUD application. I am able to send GET requests, but other requests are not getting sent.
The below line is causing error.
await Book.create(req.body);
app.js
const express = require('express');
const connectDB = require('./config/db');
const books = require('./routes/api/book');
const app = express();
connectDB();
app.use('/api/books', books);
app.get('/', (req, res) => {
res.send('<h1>Starter Code</h1>')
});
const port = process.env.PORT || 8082;
app.listen(port, () => {
console.log(`Listening on port ${port}`);
})
routes/api/book.js
const express = require('express');
const router = express.Router();
// Load book model
const { Book } = require('../../models/Book');
// #route GET api/books/test
// #description tests books route
// #access Public
router.get('/test', (req, res) => {
res.send('Book route testing!');
});
// #route GET api/books
// #description get all books
// #access Public
router.get('/', async (req, res) => {
try {
const books = await Book.find();
res.json(books);
} catch (error) {
res.status(404);
res.json({nobooksfound: 'No Books found'});
}
});
// #route GET api/books/:id
// #description get single book by id
// #access Public
router.get('/:id', async (req, res) => {
try {
const book = await Book.findById(req.params.id);
res.json(book);
} catch (error) {
res.status(404);
res.json({ nobookfound: 'No Book Found' });
}
});
// #route POST api/books
// #description add or save book
// #access Public
router.post('/', async (req, res) => {
try {
await Book.create(req.body);
res.json({msg: 'Book added successfully'});
} catch (error) {
res.status(400);
res.json({
error: 'Unable to add this book'
})
}
});
// #route PUT api/books/:id
// #description update book
// #access Public
router.put('/:id', async (req, res) => {
try {
const book = await Book.findByIdAndUpdate(req.params.id, req.body);
res.json({
msg: 'Updated Successfully'
})
} catch (error) {
res.status(400);
res.json({
error: 'Unable to update the Database'
})
}
});
// #route PUT api/books/:id
// #description delete book
// #access Public
router.delete('/:id', async (req, res) => {
try {
const book = await Book.findByIdAndRemove(req.params.id, req.body);
res.json({msg: 'Book entry deleted successfully'});
} catch (error) {
res.status(404);
res.json({error: 'No such book'})
}
});
module.exports = router;
models/Book.js
const mongoose = require('mongoose');
const BookSchema = new mongoose.Schema({
title: {
type: String,
required: true
},
author: {
type: String,
required: true
},
description: {
type: String
},
published_date: {
type: Date
},
publisher: {
type: String
},
updated_date: {
type: Date,
default: Date.now
}
});
module.exports = Book = mongoose.model('book', BookSchema);
Error is you have not used body-parser. Replace app.js code with the below one.
const express = require('express');
const bodyParser = require('body-parser');
const connectDB = require('./config/db');
const books = require('./routes/api/book');
let app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
connectDB();
app.use('/api/books', books);
app.get('/', (req, res) => {
res.send('<h1>Starter Code</h1>')
});
const port = process.env.PORT || 8082;
app.listen(port, () => {
console.log(`Listening on port ${port}`);
})
You are telling it to await. But await what. You must create a Promise to wait for.
Somewhere in you model you are going to need to create a Promise.
//here is an example so you can see the flow. I know it's mysql and not mongo, but a promise is a promis
pullWhiteList: async (phone) => {
data = new Promise((resolve, reject) => {
sql = "SELECT c.name AS client_name, w.* FROM api_whitelist w INNER JOIN api_client c ON w.client_id = c.client_id WHERE phone LIKE ? ORDER BY phone ASC LIMIT 10;";
db.query(sql, [phone + '%'], (err, res, fields) => {
if (err) {
resolve(err);
} else {
resolve(res);
}
});
})
return await data;
},

Can i add mongodb _id to localhost adress to display one post from database?

I have set up my project to display posts from a MongoDB database. My localhost address is http://localhost:5000/api/posts and it displays my two saved posts. How can I add MongoDB _id to localhost adress to only display one post?
MongoDB _id: 6061890d59ec3b6abcb011fb
I have tried this:
http://localhost:5000/api/posts/6061890d59ec3b6abcb011fb
http://localhost:5000/api/posts/id:6061890d59ec3b6abcb011fb
http://localhost:5000/api/posts/_id:6061890d59ec3b6abcb011fb
All of them returns error Cannot GET /api/posts/and_the_above_parameters_for_each_example`
Index.js to connect my backend to my application.
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
//Middleware
app.use(bodyParser.json());
app.use(cors());
const posts = require("./routes/api/posts");
app.use("/api/posts", posts);
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server started on port ${port}`));
posts.js to connect to MongoDB database. Below Password, MY_DATABASE and TABLE is changed to real values in my code.
const express = require("express");
const mongodb = require("mongodb");
const router = express.Router();
//Get posts
router.get("/", async (req, res) => {
const posts = await loadPostCollection();
res.send(await posts.find({}).toArray());
});
//Add post
router.post("/", async (req, res) => {
const posts = await loadPostCollection();
await posts.insertOne({
text: req.body.text,
createdAt: new Date(),
});
res.status(201).send();
});
router.delete("/:id", async (req, res) => {
const posts = await loadPostCollection();
await posts.deleteOne({
_id: req.params.id,
});
res.status(200).send();
});
async function loadPostCollection() {
const client = await mongodb.MongoClient.connect(
"mongodb+srv://MongoDB:PASSWORD#cluster0.5pnzd.mongodb.net/MY_DATABASE?retryWrites=true&w=majority",
{
useNewUrlParser: true,
useUnifiedTopology: true,
}
);
return client.db("MY_DATABASE").collection("TABLE");
}
module.exports = router;
PostService.js to display posts on localhost and methods to post and delete.
import axios from "axios";
const url = "http://localhost:5000/api/posts/";
class PostService {
// Get posts
static getPosts() {
return new Promise((resolve, reject) => {
axios
.get(url)
.then((res) => {
const data = res.data;
resolve(
data.map((post) => ({
...post, //spread operator
createdAt: new Date(post.createdAt),
}))
);
})
.catch((err) => {
reject(err);
});
});
}
// Create posts
static insertPost(text) {
return axios.post(url, {
text,
});
}
static deletePost(id) {
return axios.delete(`${url}${id}`);
}
}
export default PostService;
router.get("/:id", async (req, res) => {
const posts = await loadPostCollection();
res.send(await posts.findOne({
_id: req.params.id,
}));
});
Number 1: http://localhost:5000/api/posts/6061890d59ec3b6abcb011fb is correct, but you're going to need to create a new route to handle that request.
These are often called 'show' routes.
router.get("/:id", async (req, res) => {
// code to handle the logic of that request
// access the url parameter via: req.params.id
});

Heroku - Request timed out for fetching request

On localhost:5000/posts my data is successfully showing but if I do the same thing in Heroku: https://rest-in-peep.herokuapp.com/posts I get an application error. https://rest-in-peep.herokuapp.com/ works fine and I deployed it through Heroku GIT. I made sure to config my environmental vars in Heroku and added a Procfile but I am still getting this application error. I've been trying all day to figure this out but what I expect to happen is if I type in https://rest-in-peep.herokuapp.com/posts, I will get all the data that is being stored on my MongoDB database.
app.js file
const http = require("http");
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const cors = require("cors");
require("dotenv/config");
const app = express();
const server = http.createServer(app);
//Middlewares
app.use(cors());
app.use(bodyParser.json());
//Import Routes
const postsRoute = require("./routes/posts");
app.use("/posts", postsRoute);
//ROUTES
app.get("/", (req, res) => {
res.send("We are on home");
});
//Connect to DB
mongoose.connect(
process.env.DB_CONNECTION,
{ useNewUrlParser: true },
() => console.log("connected to MongoDB")
);
//How do we start listening to the server
server.listen(process.env.PORT || 5000, () => {
console.log("App now running on PORT");
});
routes>
posts.js
const express = require("express");
const Post = require("../models/Posts");
const router = express.Router();
//GETS BACK ALL THE POSTS
router.get("/", async (req, res) => {
try {
const posts = await Post.find();
res.json(posts);
} catch (err) {
res.json({ message: err });
}
});
//SUBMITS A POST
router.post("/", async (req, res) => {
console.log(req);
const post = new Post({
quote: req.body.quote
});
try {
const savedPost = await post.save();
res.json(savedPost);
} catch (err) {
res.json({ message: err });
}
});
//SPECIFIC POST
router.get("/:postId", async (req, res) => {
try {
const post = await Post.findById(req.params.postId);
res.json(post);
} catch (err) {
res.json({ message: err });
}
});
//Delete Post
router.delete("/:postId", async (req, res) => {
try {
const removedPost = await Post.remove({ _id: req.params.postId });
res.json(removedPost);
} catch (err) {
res.json({ message: err });
}
});
//Update a post
router.patch("/:postId", async (req, res) => {
try {
const updatedPost = await Post.updateOne(
{ _id: req.params.postId },
{
$set: { quote: req.body.quote }
}
);
res.json(updatedPost);
} catch (err) {
res.json({ message: err });
}
});
module.exports = router;
gitignore
/node_modules
models>Posts.js
const mongoose = require("mongoose");
const PostSchema = mongoose.Schema({
quote: {
type: String,
required: true
}
});
module.exports = mongoose.model("Posts", PostSchema);

User.find() returns empty response in mongodb express

I'm working with nextjs and express .I'm implementing simple signin form.I'm sending user credential and using find() ,checking whether user exist or not.but find() returns empty response.
In terminal find() returns array of that record.
model
const mongoose = require('mongoose')
const schema = mongoose.Schema
const user = new schema({
username: { type: String} ,
password: { type: String},
role: { type: String},
})
module.exports = mongoose.model('user', user);
router.js
const express = require('express')
const router = express.Router()
const user = require('../models/user');
router.post('/user/signin', (req, res) => {
user.find({
username: req.body.username, password: req.body.password
}, (err, user) => {
console.log(user);
if (err) {
result.status(404).send({ error: 'There is some error' });
} else if (user.length == 1) {
var token = 'kkl';//token
res.send({ token });
} else {
console.log(err);
res.send('Incorrect Email and Password');
}
});
})
module.exports = router;
this.is my index.js
const express = require('express')
const next = require('next')
const bodyParser = require('body-parser')
const PORT = process.env.PORT || 4000
const dev = process.env.NODE_DEV !== 'production' //true false
const nextApp = next({ dev })
const handle = nextApp.getRequestHandler() //part of next config
const mongoose = require('mongoose')
const router = express.Router();
nextApp.prepare().then(() => {
const app = express();
const db = mongoose.connect('mongodb://localhost:27017/knowledgeBase')
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use('/knowledgeBase', require('./routes/router'));
app.get('*', (req, res) => {
return handle(req, res) // for all the react stuff
})
app.listen(PORT, err => {
if (err) {
console.log(err);
throw err;
}
console.log(`ready at http://localhost:${PORT}`)
})
})
please help
What response you get when you try this?
According to the response I will edit response.
router.post("/user/signin", async (req, res) => {
if (!req.body.username) return res.status(400).send("username cannot be null");
if (!req.body.password) return res.status(400).send("Password cannot be null");
const user = await User.findOne({ username: req.body.username});
if (!user) return res.status(400).send("User not found");
if (req.body.password!== user.password)
return res.status(400).send("Invalid password.");
res.send("logined");
});

Resources