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....
Related
I am using MongoDB, Mongoose, Elasticsearch and Mongoosastic on a Node project. I have a MongoDB Atlas database and a local Elasticsearch database which are mapped together. When I create a new Document in MongoDB it is created in ES as well, and when I delete it in Mongo it is deleted in ES too. So everything works until this point.
What I did next is, I added an update route to update specific documents in Mongo. They do get updated but the changes are not reflected in ES because I might be missing something. Does anyone have any ideas?
Here is the Model/Schema in donation.js:
const mongoose = require('mongoose');
const mongoosastic = require('mongoosastic');
const Schema = mongoose.Schema;
const donationSchema = new Schema({
donorUsername: {
type: String,
required: true,
es_indexed:true
},
bankName: {
type: String,
required: true,
es_indexed:true
},
qualityChecked: {
type: String,
required: true,
es_indexed:true
},
usedStatus: {
type: String,
required: true,
es_indexed:true
},
}, { timestamps: true });
donationSchema.plugin(mongoosastic, {
"host": "localhost",
"port": 9200
});
const Donation = mongoose.model('Donation', donationSchema , 'donations');
Donation.createMapping((err, mapping) => {
console.log('mapping created');
});
module.exports = Donation;
Here are the create and update functions/routes in donationController.js:
const donation_create_post = (req, res) => {
console.log(req.body);
const donation = new Donation(req.body);
donation.save()
.then(result => {
res.redirect('/donations');
})
.catch(err => {
console.log(err);
});
}
const donation_update = (req, res) => {
const filter = { donorUsername: req.body.donorUsername };
const update = { bankName: req.body.bloodbankName,
qualityChecked: req.body.qualityChecked,
usedStatus: req.body.usedStatus };
Donation.findOneAndUpdate(filter, update)
.then(result => {
res.redirect('/donations');
})
.catch(err => {
console.log(err);
});
}
Solved it. Added {new: true} in Donation.findOneAndUpdate(filter, update, {new: true}).
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.
for exemple I have a user model like this
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
username: {
type: String,
required: true,
},
Points: {
type: Number,
default: 0,
},
module.exports = User = mongoose.model("users", UserSchema);
then I want to execute a function automatically when user.points is equal to 10 with express js, is there any solution ?
#Yessine, may you should try something like this. You can add checkForPoints wherever you are updating the Points and proceed with your things,
const { Users } = require('/schema.js');
const checkForPoints = async (username) => {
await Users.findOne({ username }, function (err, data) {
if (err) {
console.log("enter error ------", err)
}
if (data && data.Points === 10) {
// Execute your code
}
});
};
// Users schema(schema.js)
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect('your db', { useNewUrlParser: true });
const requestSchema = mongoose.Schema({
_id: mongoose.Types.ObjectId,
username: String,
Points: Number
});
module.exports = mongoose.model('users', requestSchema);
Polling is a technique where we check for fresh data over a given interval by periodically making API requests to a server.enables you to periodically check for the newest values of data and do further requests once it enters the desired state.
I'm using postman to make a request to my node.js API, to which I'm using my orders route to send a request following my order controller. Whatever requisition I make using my orders route my requisition hangs and instead of receiving either a 400 or a 500 response, my postman gets stuck on loading screen and it times out after some time. I tried alternatively using the google chrome extension, same results. After the requisition is unsuccessful I receive the following message
I was wondering if it has something to do with how I did the routing in my backend, but I am unsure of this. Hence, here's my code:
model.js:
'use strict';
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const schema = new Schema({
customer: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Customer'
},
number: {
type: String,
required: true
},
createDate: {
type: Date,
required: true,
default: Date.now
},
status: {
type: String,
required: true,
enum: ['created', 'done'],
default: 'created'
},
items: [{
quantity: {
type: Number,
required: true,
default: 1
},
price: {
type: Number,
required: true
},
product: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Product'
}
}],
});
module.exports = mongoose.model('Order', schema);
post method in my order-controller.js:
exports.post = async(req, res, next) => {
try {
const token = req.body.token || req.query.token || req.headers['x-access-token'];
const data = await authService.decodeToken(token);
await repository.create({
customer: data.id,
number: guid.raw().substring(0, 6),
items: req.body.items
});
res.status(201).send({
message: 'Order registered with success!'
});
} catch (e) {
console.log(e);
res.status(500).send({
message: 'Fail to process your requisition'
});
}
};
order-repository.js:
'use strict';
const mongoose = require('mongoose');
const Order = mongoose.model('Order');
exports.get = async(data) => {
var res = await Order
.find({}, 'number status customer items')
.populate('customer', 'name')
.populate('items.product', 'title');
return res;
}
exports.create = async(data) => {
var order = new Order(data);
await order.save();
}
order-route.js:
'use strict';
const express = require('express');
const router = express.Router();
const controller = require('../controllers/order-controller');
const authService = require('../services/auth-service');
router.get('/', authService.authorize, controller.get);
router.post('/', authService.authorize, controller.post);
module.exports = router;
This can happen if you are debugging your nodejs server and it's caught on a breakpoint. If so, the response will hang. To fix it, just disable that breakpoint, restart your nodejs server, and issue the request again with Postman.
Maybe you are using a GET request in the postman instead of POST request.
Make sure that they comply with the type.
I've this project folder structure:
And I'm trying to import my user schema in my user ctrl but when i start nodemon users.ctrl.js gives me this error:
const {Users} = require('users.schema');
^
SyntaxError: Unexpected token
This is the user schema:
const mongoose = require('mongoose');
const validator = require('validator');
// {
// email: 'andrew#example.com',
// password: 'adpsofijasdfmpoijwerew',
// tokens: [{
// access: 'auth',
// token: 'poijasdpfoimasdpfjiweproijwer'
// }]
// }
var Users = mongoose.model('Users', {
email: {
type: String,
required: true,
trim: true,
minlength: 1,
unique: true,
validate: {
validator: validator.isEmail,
message: '{VALUE} is not a valid email'
}
},
password: {
type: String,
required: true,
minlength: 6
},
tokens: [{
access: {
type: String,
required: true
},
token: {
type: String,
required: true
}
}]
});
module.exports = {Users}
And this is the user ctrl:
const mongoose = require('mongoose');
const {Users} = require('users.schema');
getAll = (req, res) => {
// let id = req.params.userId;
console.log('GET all cards');
Users
.find()
.select('users')
.exec((err, doc) => {
console.log('Risultato: ', doc);
});
};
module.exports = {
getAll
};
And this is the user ctrl:
const mongoose = require('mongoose');
const {Users} = require('users.schema');
getAll = (req, res) => {
// let id = req.params.userId;
console.log('GET all cards');
Users
.find()
.select('users')
.exec((err, doc) => {
console.log('Risultato: ', doc);
});
};
module.exports = {
getAll
};
Where am I wrong? Is there something that escapes me?
By default node corresponds to /node_modules where the node packages are stored. Hence use relative path names to access the file require(./filename).
I solved the problem:
On this current pc that i'm using i had node version number 5.0.7 . To use the new ecma6 features i need to install v 8.0....
After installing the version I solved the problemAfter installing the version I solved the problem