I have a sails js app,
The following codes works fine:
list: async(req, res) => {
Data.find({}).exec((err, data)=>{
if(err){
res.send(500, {message: 'db error'});
}
res.status(200).json({
message: 'Data List',
data: data
});
});
Outputs all the data of the collection correctly.
While the below code removes all the data from the mongo db collection and then shows a empty array:
list: async(req, res) => {
const data = await Data.find({});
if(!data){
res.send(500, {message: 'db error'});
}
res.status(200).json({
message: 'Data List',
data: data
});
}
I do not understand why so, I am more comfortable with async await also it makes code look cleaner hence I wanted to use the below method. Please help how can I make the below code snippet to work just like the above one.
It worked fine, when used
const data = await Data.find();
instead of
const data = await Data.find({});
Related
I've been working on one of my first API projects with NodeJS, Express and MongoDB. I can save new documents into the database with collection.insertOne(newDocument) method but I can not take existing documents and output them using collection.find({}).
Can you please help me:')
export const visualizeUser = (req, res) => {
console.log("you are searching the user with username " + req.body.username);
users.find({username: 'yavuz'}, (err, data) => {
if(err)
console.log(err);
else
console.log(data);
});
}
thats the code I have written.
MongoInvalidArgumentError: Argument "options" must not be function
and that is the error I am getting.
Your help is really appreciated.
Like error message is saying, you cannot pass function as options argument.
Look here: docs
Your code should look like this:
const visualizeUser = async (req, res) => {
try{
console.log("you are searching the user with username " +
req.body.username);
let data = await users.find({username: 'yavuz'});
console.log(data)
} catch(e) {
console.log(e)
}
}
I have been playing around with ExpressJS I normally use FastAPI. I can't seem to generate an error using Supabase.
I have this endpoint
app.delete('/api/delete-book/:id', cors(corsOptions), async (req, res) => {
const {data, error} = await supabase
.from('books-express')
.delete()
.match({id: req.params.id})
if (error) {
res.status(400).send({message: `ERROR! ${error.message}`})
}
if (data)
res.send({
message: `Book ID ${req.params.id} has been deleted from the database`,
})
})
This works when it comes to deleting a book via an ID. However if I enter an invalid ID I get the data if block firing.
There is no book with an ID of 222 in the database, I would expect the error to fire but its just null
Any ideas here?
This is expected behaviour; not matching any rows is not considered an error condition in postgres.
If you'd like to check if any rows were deleted, you can use something akin to (on supabase-js 2.x):
const { data, error } = await supabase.from('books-express')
.delete()
.match({id: req.params.id})
.select() // not needed on 1.x libs
if (error || data.length === 0) {
res.status(400).send({...})
}
I´m new to Node, Mongo and ReactJS, and I´m trying to show all the documents in my collections in the same page. But I don´t know how to call the FIND methods and which what route use, because it has to be shown in the same page. This is the code I have so far.
app.get("/home",(req,res)=>{
JobModel.find({},(err,result)=>{
if(err){
res.json(err);
}else{
res.json(result);
}
});
});
app.get("/home",(req,res)=>{
SchoolModel.find({},(err,result)=>{
if(err){
res.json(err);
}else{
res.json(result);
}
});
});
Also, like the information from the schools and jobs are almost the same (except for the name, they both have date and desciption, just the name attribute changes) the information of the jobs are duplicated but with diferent style and with no name shown(because I changed the style between them to identificate them)
You can also use the new async syntax to solve.
Your code would be like this.
app.get("/home", async (req, res) => {
const jobData = await JobModel.find().exec();
const schoolData = await SchoolModel.find().exec();
res.json({
jobData,
schoolData
})
});
There may be many approache that you have, I think a simple one is to use promise.all function in node.js
const promise1 = JobModel.find({}).exec();
const promise2 = SchoolModel.find({}).exec();
Promise.all([promise1, promise2]).then(values =>
{
console.log(values[0]) // job docs
console.log(values[1]) // school docs
res.json(values)
}
).catch(err => console.error(err))
I have a deleteMany request but I am having a hard time in filtering my context of the deleteMany returned value. It only returns 1 value deleted from pusherjs.
Here is my change stream code and pusher code in server side;
if (schedules.operationType === 'delete') {
const scheduleDetails = schedules.documentKey;
pusher.trigger('schedules', 'deleted', {
_id: scheduleDetails._id,
teamOne: scheduleDetails.teamOne,
teamTwo: scheduleDetails.teamTwo,
user: scheduleDetails.user,
isDone: scheduleDetails.isDone,
isStarted: scheduleDetails.isStarted,
date: scheduleDetails.date,
gameEvent: scheduleDetails.gameEvent,
});
}
Here is my pusher code in client side. I am using React by the way. It is stored in my context api;
ScheduleChannel.bind('deleted', ({ deletedSchedule }) => {
console.log(deletedSchedule);
setScheduleList(
scheduleList.filter((schedule) => schedule._id !== deletedSchedule._id)
);
});
here is my code on request;
exports.deleteallmatch = async (req, res) => {
try {
const { sub } = req.user;
const deletedMatches = await Schedule.deleteMany({ user: sub });
return res.status(201).json({
message: 'All of your schedule is successfully deleted!',
deletedMatches,
});
} catch (err) {
return res.status(400).json({
message: 'Something went wrong.',
});
}
};
The delete request is fine but I want to have realtime in my app. Cuz it happened that only one data is being send instead of many. How can I solve this?
The deleteMany() method returns an object that contains three fields:
n – number of matched documents
ok – 1 if the operation was successful
deletedCount – number of deleted documents
What you can do is:
First find all elements that match your query
Store them in some variable
Perform deleting
Return the stored variable
let deleted_items = await Schedule.find({ user: sub });
await Schedule.deleteMany({ user: sub });
return res.status(201).json({
message: 'All of your schedule is successfully deleted!',
deleted_items,
});
i've fetch data of single model from the database but i'm getting problem while fetching multiple model from the database. while fetching model everything related to model comes in return but i want only id and datas
this is my code
router.get('/',(req,res) =>{
const how = Howitworks.find().lean();
const value = Slider.find().lean();
console.log(how)
res.render('index', {how: how, value: value});
})
this is my code for fetching single model
router.get('/',(req,res) =>{
Howitworks.find((err,docs)=>{
if(!err){
res.render("index",{
list:docs
})
}
else {
console.log("error in retriving hoiw it works list: "+err)
}
}).lean()
})
is there any way to fetch both model?
Hi As I understood your code, your script should be like below.
router.get('/', async(req,res) =>{
const how = await Howitworks.find().lean();
const value = await Slider.find().lean();
// You can process how, values here and use then
console.log(how)
res.render('index', {how: how, value: value});
})