Api calls MEAN4+ - javascript

So i'm working in a mean stack application but i just don't get my api right..
The only thing that works is the GET !
My post and put doesn't seems to work, I think i got my syntax wrong but I just don't find the right one on the internet.
//GET
router.get('/employees', (req, res) => {
connection((db) => {
db.collection('employees')
.find()
.toArray()
.then((employees) => {
response.data = employees;
res.json(response);
})
.catch((err) => {
sendError(err, res);
});
});
});
// POST
router.post('/employees', (req, res) => {
const employees = { name: req.body.name, age: req.body.age , wage: req.body.wage , place: req.body.place };
db.collection('employees').insert(employees, (err, result) => {
if (err) {
res.send({ 'error': 'An error has occurred' });
} else {
res.send(result.ops[0]);
}
});
});
//PUT
router.put('/employees/:id', (req, res) => {
const id = req.params.id;
const details = { '_id': new ObjectID(id) };
const employee = { name: req.body.name, age: req.body.age , wage: req.body.wage , place: req.body.place };
db.collection('employees').update(details, employee, (err, result) => {
if (err) {
res.send({'error':'An error has occurred'});
} else {
res.send(employee);
}
});
});

your PUT and POST methods dont have connections to the database established so db.collection is undefined in both
router.post('/employees', (req, res) => {
const employees = { name: req.body.name, age: req.body.age , wage: req.body.wage , place: req.body.place };
connection((db) => {
db.collection('employees').insert(employees, (err, result) => {
if (err) {
res.send({ 'error': 'An error has occurred' });
} else {
res.send(result.ops[0]);
}
});
});
});
//PUT
router.put('/employees/:id', (req, res) => {
const id = req.params.id;
const details = { '_id': new ObjectID(id) };
const employee = { name: req.body.name, age: req.body.age , wage: req.body.wage , place: req.body.place };
connection((db) => {
db.collection('employees').update(details, employee, (err, result) => {
if (err) {
res.send({'error':'An error has occurred'});
} else {
res.send(employee);
}
});
});
});

Related

Node Js: Remove string array element from mongoDB

I have a user schema as follows:
const UserSchema = new mongoose.Schema({
skills: [String]
});
module.exports = mongoose.model("User", UserSchema);
And a Fetch request to delete a skill as follows:
const deleteItem = async (id) => {
try {
await fetch(`http://localhost:5000/api/user/deleteskill`, {
method: "DELETE",
headers: { "Content-Type": "application/JSON", token: accessToken },
body: JSON.stringify({ userid: userid , skill:id}),
})
.then((res) => res.json())
.then((data) => {
console.log("USER SKILLS:", data.userskills);
});
} catch (err) {
console.log(err);
}
};
Server
const deleteSkill = async (req, res) => {
try {
const user = await User.findById(req.body.userid)
//user.skills.pull(req.body.skill);
// removeskill = user.skills.filter(function(item) {
// return item !== req.body.skill
// })
if (user.skills.includes(req.body.skill)) {
res.status(400).json("Item Still Exists");
} else {
res.status(200).json("Item Deleted");
}
} catch (error) {
res.status(500).send({ error: error.message });
}
};
the array is in the following structure
[
'skill1', 'java', 'skill5'
]
I have tried to remove the user skill from the array in several ways but I still get res.status(400).json("Item Still Exists");. What I'm doing wrong?
Use the findOneAndUpdate method to find a document with the user id and update it in one atomic operation:
const deleteSkill = async (req, res) => {
try {
let message = "Item Deleted";
let status = 200;
const user = await User.findOneAndUpdate(
{ _id: req.body.userid },
{ $pull: { skills: req.body.skill } },
{ new: true }
)
if (user && user.skills.includes(req.body.skill)) {
message = "Item Still Exists";
status = 400;
} else if (!user) {
message = "User Not Found";
status = 404;
}
res.status(status).send({ message });
} catch (error) {
res.status(500).send({ error: error.message });
}
};
I believe you want to remove skills from the database then the following function could help you out.
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mydb");
var myquery = { userid: userid, skillid: skillid};
dbo.collection("skills").deleteOne(myquery, function(err, obj) {
if (err) throw err;
console.log("1 document deleted");
db.close();
});
});
You have a method of removing elements from arrays, if you want to remove the first one you could use array.shift (more on it here), but if you want to delete it completely from your database you could always, find it and then update it.
User.update({ _id: userid }, { $pull: { "skills": "[skill]" }})

How can i get list of customers between a date range?

How can i get list of customers between a date? There will be a starting date and an ending date picker in my frontend react app, but i dont know how to get the data in a specific date range uisng mongoose in my express app. Im posting my mongoose model and router code below, a little help will be appreciated --
mongoose model
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const customerSchema = new Schema(
{
name: {
type: String,
required: true,
max: 50,
},
phone: {
type: String,
required: true,
max: 12,
},
address: {
type: String,
required: true,
max: 100,
},
pin: {
type: String,
required: true,
max: 6,
},
remarks: {
type: String,
max: 50,
},
isConverted: {
type: Boolean,
default: false,
},
},
{ timestamps: true }
);
const Customer = mongoose.model(
'Customer',
customerSchema
);
module.exports = Customer;
route
const router = require('express').Router();
const Customer = require('../models/Customer');
router.post('/add', (req, res) => {
const newCustomer = new Customer({
name: req.body.name,
phone: req.body.phone,
address: req.body.address,
pin: req.body.pin,
});
newCustomer
.save()
.then((cx) => {
if (!cx) {
res
.status(400)
.send('Error creating a new customer');
} else {
res.send(cx);
}
})
.catch((err) => {
res.status(500).json({ err });
});
});
router.get('/list', (req, res) => {
Customer.find()
.then((cx) => {
if (!cx) {
res
.status(400)
.send('Error getting customer');
} else {
res.send(cx);
}
})
.catch((err) => {
res.status(500).json({ err });
});
});
router.get('/getbyphone/:phone', (req, res) => {
Customer.findOne({ phone: req.params.phone })
.then((cx) => {
if (!cx) {
res
.status(400)
.send('Error getting customer');
} else {
res.send(cx);
}
})
.catch((err) => {
res.status(500).json({ err });
});
});
router.get('/getbyname', (req, res) => {
Customer.findOne({ name: req.body.name })
.then((cx) => {
if (!cx) {
res
.status(400)
.send('Error getting customer');
} else {
res.send(cx);
}
})
.catch((err) => {
res.status(500).json({ err });
});
});
router.put('/:id', (req, res) => {
Customer.findByIdAndUpdate(req.params.id, {
remarks: req.body.remarks,
isConverted: req.body.isConverted,
})
.then((response) => {
res.send('Successfully updated');
})
.catch((err) => {
res.status(500).json({ err });
});
});
router.get('/:id', (req, res) => {
Customer.findById(req.params.id)
.then((cx) => {
res.send(cx);
})
.catch((err) => {
res.status(500).json(err);
});
});
module.exports = router;
add new route like this
router.post('/getByDate', (req, res) => {
Customer.find({ createAt:{$gt: req.body.min,$lt:req.body.max })
.then((cx) => {
if (!cx) {
res
.status(400)
.send('Error getting customer');
} else {
res.send(cx);
}
})
.catch((err) => {
res.status(500).json({ err });
});
});
and send data from front lime this
{
min:mindate,
max:maxdate
}

Sequelize MySQL update value copy from other table

I'm trying to make a controller that will do something like this:
UPDATE bankapplication_accounts
SET last_successful_logged = last_present_logged
WHERE id = 1
My controller in sequelize looks like this:
exports.updateLastLoggedDate = (req, res) => {
User.findOne({
where: {
id: req.params.userId,
},
}).then(user => {
if (user) {
User.update(
{
last_successfull_logged: user.last_present_logged,
},
{ where: { id: req.params.userId } },
).then(() => {
res.status(200).send('logout correct');
});
}
});
};
Can this controller write better?
There are 2 ways
1:
exports.updateLastLoggedDate = (req, res) => {
User.findOne({
where: {
id: req.params.userId,
},
}).then((user) => {
if (user) {
user.update({
last_successfull_logged: user.last_present_logged,
}).then(() => {
res.status(200).send("logout correct");
});
}
});
};
2:
User.update(
{
last_successfull_logged: user.last_present_logged,
}, /* set attributes' value */
{
where: {
id: req.params.userId,
},
}, /* where criteria */
).then(() => {
res.status(200).send("logout correct");
});

API testing using postman

I am developing Rest APIs for some project and testing them using postman to send the data on my mLab server. But All I could get:
{
"error": {
"message": "ENOENT: no such file or directory, open 'C:\\Users\\Admin\\Desktop\\periodical API\\uploads\\2018-06-16T14:34:38.384Zhd-wallpaper-of-live.jpg'"
}
}
Here's my route code:
const mongoose = require("mongoose");
const Product = require("../models/product");
exports.products_get_all = (req, res, next) =>
{
Product.find()
.select("name price quantity date subject _id productImage")
.exec()
.then(docs => {
const response = {
count: docs.length,
products: docs.map(doc => {
return {
name: doc.name,
price: doc.price,
quantity: doc.quantity,
date: doc.date,
subject: doc.subject,
productImage: doc.productImage,
_id: doc._id,
request: {
type: "GET",
url: "http://localhost:3000/products/" + doc._id
}
};
})
};
res.status(200).json(response);
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
};
exports.products_create_product = (req, res, next) => {
const product = new Product({
_id: new mongoose.Types.ObjectId(),
name: req.body.name,
price: req.body.price,
quantity: req.body.quantity,
date: req.body.date,
subject: req.body.subject,
productImage: req.file.path
});
product
.save()
.then(result => {
console.log(result);
res.status(201).json({
message: "Created product successfully",
createdProduct: {
name: result.name,
price: result.price,
quantity: result.quantity,
date: result.date,
subject: result.subject,
_id: result._id,
request: {
type: "GET",
url: "http://localhost:3000/products/" + result._id
}
}
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
};
exports.products_get_product = (req, res, next) => {
const id = req.params.productId;
Product.findById(id)
.select("name price quantity date subject _id productImage")
.exec()
.then(doc => {
console.log("From database", doc);
if (doc) {
res.status(200).json({
product: doc,
request: {
type: "GET",
url: "http://localhost:3000/products"
}
});
} else {
res
.status(404)
.json({ message: "No valid entry found for provided ID" });
}
})
.catch(err => {
console.log(err);
res.status(500).json({ error: err });
});
};
exports.products_update_product = (req, res, next) => {
const id = req.params.productId;
const updateOps = {};
for (const ops of req.body) {
updateOps[ops.propName] = ops.value;
}
Product.update({ _id: id }, { $set: updateOps })
.exec()
.then(result => {
res.status(200).json({
message: "Product updated",
request: {
type: "GET",
url: "http://localhost:3000/products/" + id
}
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
};
exports.products_delete = (req, res, next) => {
const id = req.params.productId;
Product.remove({ _id: id })
.exec()
.then(result => {
res.status(200).json({
message: "Product deleted",
request: {
type: "POST",
url: "http://localhost:3000/products",
body: { name: "String", price: "Number" }
}
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
};
I myself could not figure out the problem as I am a bit newbie on developing APIs.
On Linux servers ENOENT means
“No such file or directory”
said that the response you are getting is trying to let you know that,
The directory where you are trying to save, does not exist
The place of file you are looking for does not exist.
What I do recommend you is that you use your debugger tool to stop the execution before you try to get to the directory or where you try to read your file. That way you will understand where your code is failing.
Now many times when I get to this error, usually means that the directory does not exist but more frequently that you do no have permission to save the file.
Good luck, I hope it helps.
http://www-numi.fnal.gov/offline_software/srt_public_context/WebDocs/Errors/unix_system_errors.html

Getting a variable to outer scope

I'm confused by this one. First of all this is my code:
router.post('/update', (req, res, next) => {
// Todo legit credit card holding
Account.findOneAndUpdate(
{ _id: req.user._id },
{
$set: {
// username: req.body.username,
creditCardNo: req.body.cardNo,
isPremium: true,
},
},
{ upsert: true },
(err, doc) => {
if (err) {
console.log(err);
}
}
);
var newUser;
Account.findById(req.user._id,(err, doc)=>{
if(err){
console.log(err);
}
else{
newUser = doc;
}
});
console.log(newUser);
res.render('user-pannel/pannel', {
title: 'User pannel',
user: newUser,
});
});
What it does is: It gets the POST call and updates a record in the db. Now I want to basically reload the the page (res.render part) and send the new user object.
I need to send the new one, because the one in req.user is now outdated (was updated before and I'm just printing the old version).
I tried getting around the problem by doing this newUser = doc;, but for some reason the newUservariable is undefined when logged outside of the findById method. Why? If I console log the doc inside of the findById method, it returns the changed object.
I turned it into an async function and awaited its resolution with the desired value.
router.post('/update', async (req, res, next) => {
// Todo legit credit card holding
Account.findOneAndUpdate(
{ _id: req.user._id },
{
$set: {
// username: req.body.username,
creditCardNo: req.body.cardNo,
isPremium: true,
},
},
{ upsert: true },
(err, doc) => {
if (err) {
console.log(err);
}
}
);
const newUser = await new Promise((resolve, reject) => {
Account.findById(req.user._id,(err, doc) => {
if(err) reject(err);
else resolve(doc);
});
});
console.log(newUser);
res.render('user-pannel/pannel', {
title: 'User pannel',
user: newUser,
});
});

Categories

Resources