how to fetch two models in same controller in same function - node.js

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});
})

Related

express.js mongdb its showing data for the wrong call

I am trying to get data from data base for a certain creator or user, but it shows data even if the creator doesn't exists.
this is the code
app.use('/api/places', placesRoutes);
router.get('/user/:uid', placesControllers.getPlacesByUserId);
const getPlacesByUserId = async(req, res, next) => {
console.log("request data!", req.params.uid);
const userId = req.params.uid;
let places;
try {
places = await Place.find({ creater: userId });
} catch (err) {
const error = new HttpError('Something went wrong, could not find a place for the given user.',500);
return next(error);
}
if(!places || places.length === 0){
return next(new HttpError('Could not find a place for the provided userid.',404));
}
res.json({ places: places.map( place => place.toObject({ getters: true }) ) });
};
this the data entry saved in mondo db
{"_id":{"$oid":"62ab10baa6f33b1c588dfb8e"},"title":"ifel tower","description":"big tower","image":"https://pixabay.com/images/search/nature/","address":"Circular Rd, Walled City of Lahore, Lahore, Punjab 54000, Pakistan","location":{"lat":{"$numberDouble":"31.5924979"},"lng":{"$numberDouble":"74.3073198"}},"creator":"u1","__v":{"$numberInt":"0"}}
it should only show data on this url
api/places/user/u1
but it show the same data on different creator id's
data with different url
I think it's related to the typo in the following line:
places = await Place.find({ creater: userId });
I guess creater should be creator instead.

How to do 2 or more "FIND" (mongo) request in node in the same route?

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))

Reading data from mongodb using sails js removes all collection data, why?

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({});

get latest records from mongodb ,if those two records are same but the time is different

{"permit":"1905403","otp":"22","acct":"12556""timestamp":"06/12/2020 14:37:50"}
{"permit":"1905403","otp":"22","acct":"12556","timestamp":"06/12/2020 17:30:50"}
router.post('/getPermitNumberDetails', async (req, res) => {
try {
// console.log('req', req.body)
const permitNumber = req.body.permit
const permitNumberRelatedInfo = await dukePdf_Model.findOne({ "permit": permitNumber });
res.status(200).send({ permitNumberRelatedInfo: permitNumberRelatedInfo });
} catch (e) {
console.log(e);
res.status(400).send(e);
}});
In MongoDB collection, I have these two documents,the content is the same but the timestamp is different.i will be having a search bar in UI, when I type permit number as 1905403, there are two records for that particular permit. but I need to show the latest record i.e, with the latest timestamp.i have mentioned the router above..can anyone please help me

How to return different results for the same query in Express.js with Node.js?

I'm new to Node.js and Express.js and I'm wondering how to return different results with the same query based on different logics. Here is my code:
const { Student } = require('../mongoose-models/student');
const express = require('express');
const router = express.Router();
router.get('/api/students/', async (req, res) => {
const query = req.query;
const studentsList = await Student.find(query);
if (!studentsList) return res.status(404).send('No student found.');
res.send(studentsList);
});
module.exports = router;
Now, if I go to http://localhost:3000/api/students/age=20 in my browser, then it will return a list of all students that are exactly 20 in a json format (the student data is stored in MongoDB). Now, I want to implement another function that will return a list of students younger than 20 when specifying age=20. Is this possible to add this logic within the same block and how can I do it?
In express for same GET request with dynamic parameter we have
router.get('/api/students/:dynamicVariable', async (req, res) => {
// you can pass multiple parameter in url
const query = req.params.dynamicVariable
// for access then use req.params.paramsNameInUrl with ":" in from of variable
})
This is wrong way to query from database But it help for big logic
router.get('/api/students/query=:Query', async (req, res) => {
const query = req.params.Query;
const studentsList = await Student.find(query);
if (!studentsList)
return res.status(404).send('No student found.');
res.send(studentsList);
});
Your query in Postman or url
www.your-domin.com/api/students/query={"age": 20 }
// or query based on your requirement
query={"status":true}
query={"age": { $gt: 20 } }
query={"age": {$nin: [20, 30, 13]}}
use GET Request if using Post

Resources