I am trying to create a sample API of restaurants using POST but after starting API and loading it into Postman it does not show results.
router.js
const express = require('express');
const restaurantController = require('../Controllers/restaurantData');
const router = express.Router();
router.post('/restaurantFilter',(req, res) => {
restaurantController.getfilter
});
module.exports = router;
app.js
const express = require('express');
const bodyparser = require('body-parser');
const mongoose = require('mongoose');
const apiRouter = require('./Routes/router');
const port = 4005;
const app = express();
app.use(bodyparser.json());
app.use('/api', apiRouter);
mongoose.connect(
'mongodb://127.0.0.1:27017/sample',
{ useNewUrlParser: true, useUnifiedTopology: true }
).then(success => {
console.log('Connected to MongoDB');
app.listen(port, () => {
console.log(`Server started at port ${port}`);
});
}).catch(error => {
console.log(error);
});
restaurant.js (Controller)
const restaurants = require('../Models/restaurantData');
exports.getfilter = (req, res) => {
const city_name = req.body.city_name;
const cost = req.body.cost;
restaurants.find({
city_name: city_name,
cost: cost
}).then(result => {
res.status(200).json({
message: "Filtered Data",
result
})
}).catch(error => {
res.status(500).json({
message: error
})
})
}
restaurantData.js (Model)
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const restaurantSchema = new Schema({
name: {
type: String,
required: true
},
city_name:{
type: String,
required: true
},
city: {
type: Number,
required: true
},
area: {
type: Number,
required: true
},
locality:{
type: String,
required: true
},
thumb: {
type: String,
required: true
},
cost:{
type: Number,
required: true
},
address:{
type: String,
required: true
},
mealtype:{
type: Number,
required: true
},
name:{
type: String,
required: true
},
cuisine:{
type: Number,
required: true
},
type:{
type: Array,
required: true
},
Cuisine:{
type: Array,
required: true
}
});
module.exports = mongoose.model('restaurantData', restaurantSchema, 'restaurantData');
I think mostly it is the router problem but trying to know where? So, share any ideas. Thank You.
This request handler:
router.post('/restaurantFilter',(req, res) => {
restaurantController.getfilter
});
Does not actually call the getfilter function so nothing is ever sent from the POST request. You can fix that by either doing this:
router.post('/restaurantFilter', restaurantController.getfilter);
or this:
router.post('/restaurantFilter',(req, res) => {
restaurantController.getfilter(req, res);
});
Then, it looks like you also have to property export and import that getfilter() function. You appear to export it just fine in restaurant.js:
exports.getfilter = (req, res) => { ... });
But, you don't seem to be importing the controller properly as you're doing this:
const restaurantController = require('../Controllers/restaurantData');
When it looks like you should be doing this:
const restaurantController = require('../Controllers/restaurant.js');
so that you're assigning the controller the object that actually has the getfilter method on it.
Related
i have a problem with adding a collection into my database in mongodb atlas.
I have managed to import this collection before but i accidentally deleted it and now i can't upload it again. there is no error in my terminal. There for i don't know what is wrong with my code.. (image of my code and terminal are attached below)
There is anyone who might know why is this can happen?
EDIT
I tried to open a new database and my all the collections was imported to it and once again, only the product collection doesn't
//////////////////////////////////
/* require('dotenv').config({ path: '/.env' }) */
const path = require('path')
require('dotenv').config({ path: path.resolve(__dirname, '..', '.env') })
console.dir(process.env.MONGO_URI)
const mongoose = require('mongoose')
const connectDB = async () => {
try {
mongoose.connect(process.env.MONGO_URI, {
useCreateIndex: true,
useNewUrlParser: true,
useUnifiedTopology: true,
})
console.log('MongoDB connection SUCCESS')
} catch (error) {
console.error('MongoDB connection FAIL')
process.exit(1)
}
}
console.dir(process.env.MONGO_URI)
module.exports = connectDB
////////////////////////////////////////////////////////////////
require('dotenv').config()
const productsData = require('./data/products')
const connectDB = require('./config/db')
const Product = require('./models/product')
connectDB()
const importData = async () => {
try {
/* Product.deleteMany({}) */
Product.insertMany(productsData)
console.dir('Data Imported Successfuly')
process.exit()
} catch (error) {
console.log(error)
console.error('Error Ocured In Imported Data Process', error)
process.exit(1)
}
}
importData()
my model schema
const mongoose = require('mongoose')
const products = require('../data/products')
const productSchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
description: {
type: String,
required: true,
},
price: {
type: Number,
required: true,
},
countInStock: {
type: Number,
required: true,
},
imageUrl: {
type: String,
required: true,
},
})
module.exports = mongoose.model('Products', productSchema)
my code and terminal image
Product.insertMany(productsData) returns a promise, but you aren't waiting for that promise to finish before exiting the process. Add an await before it and you should be okay.
Try this to create your schema instead
const { Schema } = mongoose;
const productSchema = new Schema({
name: {
type: String,
required: true,
},
description: {
type: String,
required: true,
},
price: {
type: Number,
required: true,
},
countInStock: {
type: Number,
required: true,
},
imageUrl: {
type: String,
required: true,
},
})
const Product = mongoose.model("Product", productSchema);
Product.createCollection();
I keep getting a 404 when I am posting to a route. I am using MongoDB, express and React Native. I have created the Schema, actions and router.
The Schema is below:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
// Create Edible Schema
const EdiblesSchema = new Schema({
name: {
type: String,
required: true
},
price: {
type: String,
required: true
},
strength: {
type: String,
required: true
},
purchasedLocation: {
type: String,
required: true
},
effects: {
type: String,
required: true
},
strain: {
type: String,
required: true
},
});
module.exports = Edibles = mongoose.model("edibles", EdiblesSchema);
Then the post router is below:
const express = require("express");
const router = express.Router();
const keys = require("../../config/keys");
// Load edibles model
const Edibles = require("../../models/edibles");
// #route POST api/users/edibles
// #desc Add an edible to the users collection
// #access Public
router.post ('/edibles', (req, res) => {
if (res.status === 200) {
const newEdible = new Edibles({
name: req.body.name,
price: req.body.price,
strength: req.body.strength,
strain: req.body.strain,
purchasedLocation: req.body.purchasedLocation,
effects: req.body.effects,
})
} else {
return res.status(400).json({ email: "Thats not going to get you high" });
} newEdible
.save()
.then( edibles => res.json(edibles))
.catch(err => console.log(err))
});
module.exports = router;
Then the finale we have the handleSubmit to send the users info to the api endpoint.
const handleSubmit = (response) => {
console.log("EDIBLES", name, strength, price, effects, strain)
dispatch(setEdible(payload))
if (response === 200) {
axios
.post(edibleApi, payload)
console.log("PAYLOAD", edibleApi, payload, setEdible)
// navigation.navigate("Dashboard")
} else {
console.log("WRONG", edibleApi, payload, setEdible);
console.log("userEdibles", userEdibles)
}
}
I am really lost with this... Please help!
The issue was that I was using the wrong endpoint. I worked this out by using the express-list-routes by adding it to my server.js file.
const expressListRoutes = require('express-list-routes');
const router = express.Router();
console.log("Now we cooking with gas", expressListRoutes(app, { prefix: '/api/v1' })))
That console.log must be added to the console.log that indicates if your server is running or not....
Well, I'm trying to get a value of property from a object with Mongoose find(), but for some reason, the mongoose are returning a undefined value.
The Schema:
const mongoose = require('mongoose');
const uuid = require('uuid');
const Schema = mongoose.Schema({
dsID: { type: String, unique: true, require: true },
dsTag: { type: String },
mcCode: { type: String, default: () => uuid.v4(), unique: true, select: false },
mcConnected: { type: Boolean, default: false }
}, { versionKey: false });
const Members = mongoose.model("Members", Schema);
module.exports = Members;
The code
// Database connection
mongoose.connect(DATABASE.uri, DATABASE.options);
Members.find({ 'dsID': dsID }, (err, member) => {
const connected = member.mcConnected;
console.log(connected)
});
This might be because of you should not name a model 'Schema'. Try with other name because "Schema" is reserved word
Use this code on schema
const mongoose = require('mongoose');
const uuid = require('uuid');
const memberSchema = new mongoose.Schema({
dsID: { type: String, unique: true, require: true },
dsTag: { type: String },
mcCode: { type: String, default: () => uuid.v4(), unique: true, select: false },
mcConnected: { type: Boolean, default: false }
}, { versionKey: false });
const Members = mongoose.model("Members", memberSchema);
module.exports = Members;
Here u go boys:
const app = express()
const port = 3000
//MongoDB Connection
const DB_Connect = require('./(8.1)MongoDB_Connection')
const DB = DB_Connect() //returning a Model
//Middleware
const logger = function(req, res, next) {
console.log('logging')
next()
}
app.use(logger)
//Routes
app.get('/', async(req, res) => {
console.log(DB.then((docs) => {
console.log(docs.find({ name: 'POCO X3 Pro' }, (error, docs) => {
if (error) {
console.log("Error: " + error)
} else {
console.log(docs)
}
}))
}))
})
/*
DB is a Model and console.log(DB) gives : " Promise { Model { users } } ".
But for Promise we use .then() for result.
Model { users }
As we use .find(), we got the answer
*/
//Listening
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
//Muhammad Irtaza Ghaffar (Pakistan)
Thanks me later!
So I'm currently learning how to build a Rest API with Node Js and MongoDB, so naturally I've been following some tutorials, and when the time came, I've setup an example but it doesn't work.
I have 2 main files, app.js and historic.js (model).
On app.js I have the following:
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
app.use(bodyParser.json());
Historic =require('./models/historic');
// Connect to Mongoose
mongoose.connect('mongodb://localhost/test', { useMongoClient: true });
var db = mongoose.connection;
console.log('Here');
db.on('error', function(err){
if(err){
console.log(err);
throw err;
}
});
db.once('open', function callback () {
console.log('Mongo db connected successfully');
});
app.get('/', (req, res) => {
res.send('Please use /api/historic');
});
app.get('/api/historics', (req, res) => {
Historic.getHistorics((err, historic) => {
if(err){
throw err;
}
res.json(historic);
});
});
app.listen(27017);
console.log('Running on port 27017...');
Then on my model I have the following:
const mongoose = require('mongoose');
// Historic Schema
const historicSchema = mongoose.Schema({
_id:{
type: String,
required: true
},
url:{
type: String,
required: true
},
price:{
type: String,
required: true
},
timestamp:{
type: String,
required: true
}
});
const Historic = module.exports = mongoose.model('Historic', historicSchema);
// Get Historics
module.exports.getHistorics = (callback, limit) => {
console.log('Get Historics-Historic');
Historic.find(callback).limit(limit);
console.log('Get Historics-Historic-After find');
console.log(limit);
}
Whenever I try to access http://localhost:27017/api/historics/ I only get: [].
I know that I have data on my DB as you can see on the image:
data on DB test
Any tips?
According to Docs http://mongoosejs.com/docs/2.7.x/docs/finding-documents.html the callback should be at least the 2nd parameter of the .find method.
Try to replace
// Get Historics
module.exports.getHistorics = (callback, limit) => {
console.log('Get Historics-Historic');
Historic.find(callback).limit(limit);
console.log('Get Historics-Historic-After find');
console.log(limit);
}
to
// Get Historics
module.exports.getHistorics = (callback, limit) => {
var query = Historic.find({});
query.limit(limit);
query.exec(callback);
}
I've been told the solution and it works.
Old Code:
const historicSchema = mongoose.Schema({
_id:{
type: String,
required: true
},
url:{
type: String,
required: true
},
price:{
type: String,
required: true
},
timestamp:{
type: String,
required: true
}
});
Solution:
const historicSchema = mongoose.Schema({
_id:{
type: String,
required: true
},
url:{
type: String,
required: true
},
price:{
type: String,
required: true
},
timestamp:{
type: String,
required: true
}
}, {collection: 'historic'});
I needed add the collection name that was defined on Mongoose
I have the following files. I have a recipe.js file which outlines the Mongoose Schema for a recipe and the comments for a recipe. The code for it goes as follows:
const express = require('express');
const mongoose = require('mongoose');
const User = require('../models/user');
let Schema = mongoose.Schema;
let commentSchema = Schema({
rating: {
type: Number,
// required: true,
min: 1,
max: 5,
},
recipeItem: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Recipe'
},
comment: {
type: String,
// required: true
},
postedBy: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
likedBy: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
favouredBy: {
type: mongoose.Schema.Types.ObjectId
}
});
let Comment = mongoose.model('Comment', commentSchema);
let recipeSchema = Schema({
name: {
type: String,
required: true
},
description: {
type: String,
},
steps: {
type: String,
required: true,
},
ingredients: {
type: Array,
required: true
},
comments: [commentSchema],
category: {
type: String,
required: true,
},
postedBy: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
});
/// So I learnt that by defining the string as "Recipe" in the model function, I will have to lower case it
/// and pluralize it when I use it with res.json and other such things (i.e. "Recipe" => recipes).
let Recipe = mongoose.model('Recipe', recipeSchema);
module.exports = Recipe;
module.exports = Comment;
/// refactor this so that these are in the router, not in the models file
/*
module.exports.getRecipeByName = (name, callback) => {
let nameQuery = {name: name};
Recipe.findOne(nameQuery, callback);
};
module.exports.getRecipesByCategory = (category, callback) => {
Recipe.find({'category': category});
};
*/
I also have a user.js file where I outline a a User model and the relation it has to the other models/schemas. The code in the file is as follows:
const express = require('express');
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const passportLocalMongoose = require('passport-local-mongoose');
const passport = require('passport');
let Schema = mongoose.Schema;
let User = Schema({
name: {
type: String
},
// The passport plugin already inputs username and password into our Schema
username: {
type: String,
unique: true,
required: true
},
password: {
type: String,
required: true,
},
profilePic: {
type: String
},
email: {
type: String,
unique: true,
required: true
},
admin: {
type: Boolean,
defualt: false
},
usersRecipes: [{type: Schema.Types.ObjectId, ref:'Recipe'}],
userComments: [{type: Schema.Types.ObjectId, ref: 'Comment'}],
usersFavouriteRecipes: [{type: Schema.Types.ObjectId, ref: 'Recipe'}],
usersLikedRecipes: [{type: Schema.Types.ObjectId, ref: 'Recipe'}]
});
let options = ({missingPasswordError: "Incorrect password, try again"});
User.plugin(passportLocalMongoose, options);
module.exports = mongoose.model('User', User);
And here is recipeRouter.js, the file where I define all the HTTP requests and routes:
const express = require('express');
const passport = require('passport');
const Recipe = require('../models/recipe');
const jwt = require('jsonwebtoken');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const verification = require('../verification');
const Comment = require('../models/recipe');
// I temporarily removed verification.checkIfUserExists to see if all this database stuff works
router = express.Router();
router.use(bodyParser.json());
router.get('/', (req, res) => {
res.json('Here are the recipes!')
});
router.get('/showrecipes', (req, res) => {
Recipe.find({}).populate('Comment').exec((err, recipes) => {
if (err) throw err;
res.json(recipes);
})
});
router.get("/showrecipes/:recipeId", (req, res) => {
let nameQuery = {_id: req.params.recipeId};
Recipe.findOne(nameQuery, (err, recipes) => {
if (err) throw err;
res.json(recipes);
})
//// Don't know if this is correct
.populate('comment.recipeItem');
});
router.get('/showrecipes/category/:categoryname', (req, res) => {
let nameQuery = {category: req.params.categoryname};
Recipe.find(nameQuery, (err, recipes) => {
if (err) throw err;
res.json(recipes);
});
});
router.post('/addrecipe', (req, res, next) => {
Recipe.create({
name: req.body.name,
description: req.body.description,
steps: req.body.steps,
ingredients: req.body.ingredients,
category: req.body.category
}, (err, recipes) => {
if (err) throw err;
res.json(recipes);
});
});
// See if this works
router.put("/showrecipes/:recipeId", (req, res) => {
let query = {_id: req.params.recipeId};
Recipe.findByIdAndUpdate(query, {
$set: req.body
}, {
new: true
}, (err, recipe) => {
if (err) throw err;
res.json(recipe)
})
});
router.delete("/showrecipes/:recipeId", (req, res) => {
let query = {_id: req.params.recipeId};
Recipe.findByIdAndRemove(query, (err, recipe) => {
if (err) throw err;
res.send('Recipe was succesfully deleted');
})
});
router.get("/showrecipes/:recipeId", (req, res) => {
let nameQuery = {_id: req.params.recipeId};
Recipe.findOne(nameQuery, (err, recipes) => {
if (err) throw err;
res.json(recipes);
})
.populate('comments')
.exec((err) => {
if (err) throw err;
})
});
router.post("/showrecipes:/:recipeId/addcomment", (req, res, next) => {
Comment.create({
rating: req.body.rating,
comment: req.body.comment,
postedBy: postedBy,
date: Date.now(),
recipeItem: recipeId
})
});
router.get('/showrecipes/byuser/:username', (req, res) => {
let query = {postedBy: req.params.username};
Recipe.find(query, (err, recipes) => {
if (err) throw err;
res.json(recipes)
})
});
module.exports = router;
Now, at some point I was able to create recipes and store them in my database without a problem. But now this weird thing happens.
Here, I make my post request as you can see in the screenshot below:
But for some strange reason, everytime I make a get request, none of the key/value pairs I specified in my json body request are there. Each recipe object now only as the _id in it.
Can anyone help me? This just seems so weird.
Looks like you're simply missing the application/json Content-Type header.
In Postman, just set the header, as shown in this gif.