I just making delete query to mysql with sequelize.
const model = require('../../../config/model/index');
const controller = {};
controller.drop = async function(req, res) {
try {
await model.activitys.destroy({
where: {
id: req.params.id
}
})
check_id = model.activitys.findAll({
where: {
id: req.params.id
}
})
if(check_id!=null){
res.status(200).json({
status: "Success",
message: "Success",
data: {}
})
}else{
res.status(404).json({
status: "Not Found",
message: `Activity with ID ${id} Not Found`,
data: {}
})
}
} catch (error) {
res.status(404).json({
status: "Error",
message: error.message
})
}
}
module.exports = controller;
I want to delete the data on DB from id parameters, it's work for deleting the data. But when I try to delete by id that not exist in my DB, it's still get the 200 status code.
How to make that will return 404 status code if there's no data exists in DB ?
If you want to check if a single record exists in DB then use findOne or findByPk instead of findAll. findAll always returns an array (either empty or not) and that means it's always not equal to null:
check_id = model.activitys.findOne({
where: {
id: req.params.id
}
})
Related
I don't quite understand why my requests are not added to my DB. I have schema with nested objects. So I try to send requst to specific object inside of an object. Result says scucces, however nothing is added.
Here's schema:
const personSchema = new mongoose.Schema({
connections: {
parents: {type : Array},
children: {type : Array}
}
})
Here's router:
router.patch('/v2/:id', getPerson, async (req, res) => {
if (req.body.connections != null) {
if (req.body.connections.parents != null) { res.person.connections.parents.push(req.body.connections.parents); }
if (req.body.connections.children != null) { res.person.connections.children.push(req.body.connections.children); }
}
try {
const updatePerson = await res.person.save();
res.status(200).json({ message: 'Success' })
} catch (error) {
res.status(400).json({ message: error.message })
}
})
Here's middelware:
async function getPerson(req, res, next) {
let person;
try {
person = await Person.findById(req.params.id);
if (person === null) {
return res.status(404).json({ message: 'Cannot find the person' });
}
} catch (error) {
return res.status(500).json({ message: error.message });
}
res.person = person;
next();
}
Here's request:
PATCH http://localhost:3100/api-db/v2/62e28682cecc9120c7af9de5
Content-Type: application/json
{
"connections.parents" : "test"
}
Connection is established, document in db is alredy created.
It seems to me that I might doing wrong requst. I couldn't find information about nested requsts though.
What seems to be the problem?
P.S.
Other requsts that are not nested are satisfied...
Nvm, I am just retarded:
{
"connections" : {"parents" : "test"}
}
Why is it that my first statement always returns false when I make up a code that doesn't exist in the "Courses" collection?
// POST /api/my/courses
app.post('/api/my/courses', function(req, res) {
let courseCode = req.body.courseCode.toUpperCase();
let status = req.body.status;
if (!Courses.findOne({ courseCode })) {
res.status(404).send({ "message": "Course not found." })
} else {
let course = new MyCourses({
courseCode: courseCode,
status: status
});
course.save(function(err) {
if(err) return console.error(err);
});
res.status(201).send({ "message": "New course added." });
}
});
You should await for findOne and save as they both return promises. Or, you can also pass in a callback function to findOne as the 2nd argument.
Refer to this
I'm trying out this code to create a simple order and then when trying to assign the user.shoppingCart Array to a new variable ("products") it says the user is undefined but for example the address is working just fine and then trying to console.log the user.address and user.shoppingCart it actually prints the correct values. Any ideas?
exports.createOrder = async (req, res) => {
try {
const user = await User.findById(req.user.id);
if (user.shoppingCart.length < 1) {
return res.status(400).json({
status: 'fail',
message: 'Please first add a product to your shopping cart.',
});
}
const address = req.body.address || user.address;
const products = user.shoppingCart;
const total = await getTotal();
const { paymentMethod } = req.body;
const order = await Order.create({
address,
user: user._id,
products,
total,
paymentMethod,
});
res.status(201).json({
status: 'success',
data: {
order,
},
});
} catch (err) {
res.status(500).json({
status: 'fail',
message: err.message,
});
}
};
I am new to nodeJs but I already make research in order to solve my issue but it seems that I lacking a bit in async functionalities.
I have found this solution but it does not work which I will post it down below :
enter link description here
Here is my code
router.put("/placeOrder", [auth, isVerified, isExists], async (req, res) => {
try {
const productList = req.body; // body
await Promise.all(
productList.map(async (element) => {
// compare between the inserted element and the store one here
let getItemPrice = await Order.findOne({
_id: element._id,
buyerId: req.user._id,
orderStatus: "PENDING",
});
if (!getItemPrice) {
return res.status(400).json({
status: "failed",
message: "order not exists",
});
}
getItemPrice.items.map(async (item) => {
await Order.findOneAndUpdate(
{
"items.productId": item.productId,
},
{
$set: {
orderStatus: "ACTIVE",
"items.$.itemStatus": "ACTIVE",
paymentMethod: element.paymentMethod,
},
}
);
});
})
);
res.status(200).json({
message: "Order has placed",
});
} catch (error) {
return res.status(400).json({
status: "failed",
message: error.message,
});
}
// update documents
});
I am trying to check if the Id does not exist within my array if not exists just through an error that Id does not exist, it is working fine but it keeps print error to the logs that say:
TypeError: Cannot create property 'Symbol(level)' on string 'Cannot set headers after they are sent to the client'
Thanks for your time and collerations
You cannot send multiple responses.
productList.map(async (element, i) => {
// compare between the inserted element and the store one here
let getItemPrice = await Order.findOne({
_id: element._id,
buyerId: req.user._id,
orderStatus: "PENDING",
});
getItemPrice && getItemPrice.items.map(async (item) => {
await Order.findOneAndUpdate(
{
"items.productId": item.productId,
},
{
$set: {
orderStatus: "ACTIVE",
"items.$.itemStatus": "ACTIVE",
paymentMethod: element.paymentMethod,
},
}
);
});
}
I have a code where I am updating my schema object with request body. I have applied validation rules on the schema. The problem is, I want the schema to throw an error when there's a non existing field in the request body. Non existing key doesn't save to the database as I want but I want to throw some error instead of saving the object. Schema:
const peopleSchema = new mongoose.Schema(
{
fullname: {
type: String,
required: [true, "fullname is required"],
validate: [(value) => isAlpha(value, "en-US", {ignore: " "}), "name should be alphabetic only"],
},
phone: {
type: String,
validate: [isPhone, "please enter a valid phone number"],
},
address: String,
},
{ timestamps: true }
);
Code to update person:
router.put("/:id", checkUser, async (req, res, next) => {
try {
const { id } = req.params;
const user = req.currentUser;
const person = user.people.id(id);
person.set(req.body);
const response = await user.save();
res.json({ response });
} catch (err) {
next(new BadRequestError(err));
}
});
for validation there are two way based on callback and async approache ,
because your code is based on async/await you must to use validateSync() like the following code:
let errors = user.validateSync()//check validation
if(errors){
console.log(errors)
throw errors;//handle your error
}
const response = await user.save()
in callback method :
user.save(function(err,response){
if (err){
console.log(err);
//handle error
}
else{
console.log(response)
res.json({ response });
}
})