i use following code that contain get all data get data by id and post data to mongo:
const express = require("express");
const app=express();
const _route=require('./router/router.js')
require('dotenv').config();
require('./Database/config.js');
const bodyParser=require('body-parser');
const router=express.Router();
const port_=process.env.PORT|| 8080;
const product=require('./model/model.js');
const res = require("express/lib/response");
const { db } = require("./model/model.js");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.post('/insert',async(req,res)=>{
const newProduct=new product({
_id:req.query._id,
name:req.query.name,
description:req.query.description
});
try{
await newProduct.save();
res.json(newProduct);
}
catch(err){
res.send(err);
}
});
app.get('/',async(req,res)=>{
try{
const get= await product.find();
res.json(get);
}
catch(err){
res.send(err);
}
});
app.get('/:name',async(req,res)=>{
try{
const get=await product.find({name:req.params.name});
if(get.length===0)
{
res.send(`Do not find product with name : ${req.params.id}`);
}
else{
res.json(get);
}
}
catch(err){
res.send(err);
}
});
app.listen(port_,'localhost',()=>{ console.log(`App run on port ${port_}`)});
when i enter following in address bar for insert data to mongo:
localhost:3000/insert?_id=36987&name=GLX&description=iranian smart phone
when use app.post(...) data does not post to mongo and app.get('/:name',async(req,res)
run. whenever use app.use('/insert',...) instead of app.post() data successfully posted to database.
What command should I use? What's my code problem?
Related
I'm very new to MERN so I'm trying to figure out how to use schema correctly within my backend. I'm trying to just make a very simple case here where I just create a new user document in the database. I'm not trying to do anything with auth yet I just want to figure the syntax i guess behind why my code is not communicating correctly with the db.
When I run my backend code it says I successfully am running on port 4000 and that I've connected to my database.
When I check my routes with Postman it seems to time out and return bad request.
Here is my Schema code
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
name: {type:String, required:true},
balance: {type:Number, required:true},
currentLimit: {type:Number, required:true},
maximumLimit: {type: Number, required:true, default:50}
});
module.exports = mongoose.model('user', userSchema);
This is where I make the call to the database in my router function
const express = require('express');
const User = require('../Models/user');
const userInfo = express.Router();
userInfo.route('/userInfo').get(
async function (req, res) {
await User.find().then((err, results) => {
if (err) throw err;
res.json(result);
})
}
);
userInfo.route('/makeUser').post(
async function (req, res) {
const { name, balance, currentLimit, maximumLimit } = req.body;
try {
const user = await User.create({ name, balance, currentLimit, maximumLimit });
res.status(200).json(user);
} catch (error) {
res.status(400).json(error);
console.log('error');
}
}
);
module.exports = userInfo;
This is my connection code
const { MongoClient } = require('mongodb');
const Db = process.env.URI;
const client = new MongoClient(Db, {
useNewUrlParser: true,
useUnifiedTopology: true
});
module.exports = {
connectToDatabase: async function (callback) {
try {
client.connect();
console.log('Succesfully Connected to Database');
} catch (e) {
console.error(e);
}
}
}
This is my index file
const express = require('express');
const cors = require('cors');
require('dotenv').config({path: "./config.env"});
const PORT = process.env.PORT || 4000;
const app = express();
app.use(cors());
app.use(express.json());
app.use(require('./routing/userInfo'));
const dbo = require("./DB/connection");
app.listen(PORT, ()=>{
console.log(`Server is running on port ${PORT}.`);
dbo.connectToDatabase(function (err){
if (err) console.error(err);
})
})
I feel like I've read so many mongodb schema docs and I do exactly as the docs say but still fail to read or write to/from the db.
You should await client.connect():
module.exports = {
connectToDatabase: async function (callback) {
try {
await client.connect();
console.log('Succesfully Connected to Database');
} catch (e) {
console.error(e);
}
}
};
Also, make sure you are connected to the database before starting the service:
dbo.connectToDatabase(function (err){
if (err) {
console.error(err);
process.exit(1);
}
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});
})
Finally, in the get route you are mixing await with then:
userInfo.route('/userInfo').get(async function (req, res) {
const result = await User.find();
res.json(result);
});
my code was perfectly working a couple of days ago and it suddenly stopped working it's connected to the mongodb cluster but i fail to receive response from the database everytime i send a request it's i tried reinstalling node reinstalling mongoose updating all packages but nothing seemed to work
keeps loading forever
and no response when i cancel it
here's the server.js code :
const express = require('express');
const bodyParser = require('body-parser');
const morgan = require('morgan');
const mongoose = require('mongoose');
const cors = require('cors')
require('dotenv/config');
const authJwt = require('./helpers/jwt')
const errorHandler = require('./helpers/error-handler')
const api = process.env.URL;
mongoose.connect(process.env.DATABASE,
{
useNewUrlParser:true,
useUnifiedTopology:true
})
.then(()=>{
console.log('connected to database')
})
.catch((err)=>{
console.log(err)
})
//variables
const app = express();
const port = 9090
//middleware calls
app.use(bodyParser.json());
app.use(morgan('tiny'));
app.use(express.Router())
//app.use('')
app.use(cors());
app.options('*',cors())
app.use(errorHandler)
app.use(authJwt)
const categoriesRouter = require('./routers/categories')
const productsRouter = require('./routers/products')
const ordersRouter = require('./routers/orders')
const usersRouter = require('./routers/users')
//Routers
app.use(`${api}/categories`,categoriesRouter)
app.use(`${api}/products`,productsRouter)
app.use(`${api}/users`,usersRouter)
app.listen(port,(req,res)=>
{
console.log('server is running in port '+ port )
})
here's one of the routers code :
const {Category} = require('../models/category')
const express = require('express');
const router = express.Router();
router.get('/',async(req,res)=>{
const categoryList = await Category.find();
if(!categoryList)
{
res.status(500).json({success:false})
}
res.status(200).send(categoryList);
})
router.get('/:id',async(req,res)=>{
const category = await Category.findById(req.params.id)
if(!category)
{
res.status(500).json({message:'The category with the given ID'})
}
res.status(200).send(category)
})
router.post('/',async(req,res)=>{
let category = new Category({
name:req.body.name,
icon:req.body.icon,
color:req.body.color
})
category = await category.save();
if(!category)
return res.status(404).send('the fag category cannot be created')
res.send(category)
})
router.delete('/:id', (req,res)=>{
Category.findByIdAndRemove(req.params.id).then(category=>{
if(category)
{
return res.status(200).json({success:true,message:'the category is deleted'})
}
else
{
return res.status(404).json({success:false,message:'the category is not found'})
}
}).catch(err=>{
return res.status(400).json({success:false , error: err})
})
})
router.put('/:id',async (req,res)=>{
const category = await Category.findByIdAndUpdate(
req.params.id,
{
name:req.body.name,
icon:req.body.icon,
color:req.body.color
},
//i want to return the new updated data
{ new:true }
)
if(!category)
{
return res.status(400).send('The category cannot be created!');
}
res.send(category);
})
module.exports = router;
just to let you know it was working a couple of days ago and now it just suddenly stopped working if there's anything i can do or if you've faced the same problem before please reach out
Make sure to send a proper response on the api side of code.
In the case that u are using the express framework, it could look something like this:
router.get('/', (req, res) => {
res.status(200).json({
your: data
})
})
I'm creating my first API, I've used .env for database variables in this url:
const uri = `mongodb+srv://${mongo_user}:${mongo_pwd}#cluster0.ynvbj.mongodb.net/${mongo_db}?retryWrites=true&w=majority`
then created the client:
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true })
Then, a main function that calls the functions that finds data from Mongo like users:
async function main() {
try {
await client.connect();
await getUser(client, 'users', mongo_db);
} catch (e) {
console.error(e);
} finally {
await client.close();
}
}
main().catch(console.err);
//------GET
//user by Dni
async function getUser(client, coll, mongo_db){
const collection = await client.db(`${mongo_db}`).collection(`${coll}`)
.find({dni: 38383838}).toArray(function(err, results) {
console.log(results);
return results;
})
};
And finally, I created the routes, but I get undefined. I've check everything and I don't get what's wrong.
const {getUser, getOrder, getProducts} = require('./db_connection')
const {Router} = require('express')
const router = Router()
//GET
//get user
router.get('/users', async (req, res) => {
let data = await getUser;
res.json({data});
})
module.exports = router;
And this is app.js
const express = require('express')
const app = express()
require('dotenv').config();
//settings
app.set('port', process.env.PORT || 3000)
//middlewares
app.use(express.urlencoded({extended:false}))
app.use(express.json())
//server
app.listen(app.get('port'), ()=> {
console.log(`Server running on port ${app.get('port')}`)
})
//require api
app.use('/api', require('./api_routes'))
It looks like your results are undefined, that could be for a lot of different reasons.
Where you have console.log(results) can you replace that with console.debug(err, results);
That might give you more insight into the reason it's not getting the results.
async function getUser(client, coll, mongo_db){
const collection = await client.db(`${mongo_db}`).collection(`${coll}`)
.find({dni: 38383838})
.toArray(function(err, results) {
console.debug(err, results);
return results;
})
};
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});
}
});
I am trying to insert data in MongoDb using NodeJs but before inserting data I want to check whether data is already available in database or not if data is not available then only it should insert data in MongoDb.
Problem - Whenever I am saving data even though it is not available in database it is always showing
response "User exists".
This is what I have done so far:
const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser');
const dotEnv = require('dotenv').config();
const MongoClient = require('mongodb').MongoClient;
const dburl = process.env.URL;
router.use(bodyParser.json());
router.use(bodyParser.urlencoded({extended:true}));
router.post('/saveSalesperson',(req,res) => {
var data = {
email:req.body.username,
password:req.body.password,
type:req.body.type
};
MongoClient.connect(dburl,{useNewUrlParser:true,UseUnifiedTopology:true},(err,client) => {
if(err){
console.log("Error",err);
}
else{
client.db('Mydb').collection('Users').findOne({email:req.body.username},function(err,user){
if(err){
console.log("Error",err);
}
if(user){
res.send("User exists");
}
else{
let collection = client.db("Mydb").collection("Users");
collection.insertOne(data,(err,resp) => {
if(err){
console.log("Error:".red +err);
}
else{
res.send("User created");
}
});
}
});
}
});
});
module.exports = router;
Someone please let me know what I am doing wrong.Any help would be appreciated.
THANKS