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)
}
}
Related
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 am working on a project that requires me to redirect the user to a new page after a mysql query. For some reason it works throughout the rest of the program but in this particular section, it just does nothing.
Here is my code that doesn't work.
No idea what im missing here...
exports.ad_dash_load = async (req, res) => {
var uid=req.body.User_id;
db.query('SELECT COUNT(*) AS `z`FROM `user`', async (error, results)=>{
if(error) {
console.log(error);
} else {
let user_count=results[0].z;
res.status(200).redirect("/admin?Id="+uid+"&user_count="+user_count);
}
})
}
So there are 2 other ways we can execute this query
OPTION 1
Save the result into a variable that comes from the query and then check if the var has the result
exports.ad_dash_load = async (req, res) => {
var uid = req.body.User_id;
const result = await db.query("SELECT COUNT(*) AS `z`FROM `user`");
if (!result) {
console.log(error);
} else {
let user_count = results[0].z;
res.status(200).redirect("/admin?Id=" + uid + "&user_count=" + user_count);
}
};
OPTION 2
Using this method is equivalent to using try catch block
Use .then().catch() block on the async db query
exports.ad_dash_load = async (req, res) => {
var uid = req.body.User_id;
db.query("SELECT COUNT(*) AS `z`FROM `user`")
.then((result) => {
let user_count = results[0].z;
res
.status(200)
.redirect("/admin?Id=" + uid + "&user_count=" + user_count);
})
.catch((err) => {});
};
Ok i think i understand the root of this problem....the "exports" function is supposed to be triggered from a Form POST on a previous page but because i was not moving from a page with a form i opted to use a javascript routine to send user id code to the "exports" function. This fact is responsible for the redirect not working. Trying to figure out another way around this.
I wrote this function to get a document from the end of the collection in MongoDB. When I try calling this function in index.js, it returns undefined.
index.js:
app.get('/', authenticate, function(req, res){
// console.log("DATA: " + getWorldStatsData());
everything = {
worldstats: getWorldStatsData(),
}
res.render('index', {
data: everything
})
})
and my function:
function getWorldStatsData(){
db.collection('worldstats').find({}).sort({"statistic_taken_at":-1}).limit(1).toArray((err, stats)=>{
return stats
})
// return stats
}
As jonrsharpe suggested, this is happening because the code that fetches the data is asyncroous.
That means you need to implement some kind of callback to notify the surrounding function when the operation is complete
A simple example:
index
app.get('/', authenticate, async function(req, res){
// console.log("DATA: " + getWorldStatsData());
everything = {
worldstats: await getWorldStatsData(),
}
res.render('index', {
data: everything
})
})
your funciton:
function getWorldStatsData(){
return db.collection('worldstats').find({}).sort({"statistic_taken_at":-1}).limit(1).toArray((err, stats)=>{
return stats
})
// return stats
}
Please take a look at the link provided by jonrsharpe for a better understanding
I want to bind params in node js and this is my code but shows some erros,
app.get("/single/:id", async (req, res) => {
let id = req.params.id;
console.log(id);
try{
const singleMovie = await Movies.findById(id)
res.render("single", {
singleMovie: singleMovie
});
}catch(err){
console.error(err.message);
}
});
shows me this warning,
Cast to ObjectId failed for value "undefined" at path "_id" for model
"Movies" and id is undifined
any way to fix this?
In your code res.render("single", { should be res.json("single", {
Try the code below... sending the response in json just to test it....
if you get the same error you are getting, then there is a problem somewhere in your code. Because The block of code you posted looks fine!
app.get("/single/:id", async (req, res) => {
let id = req.params.id;
console.log(id);
try{
const singleMovie = await Movies.findById(id)
res.json({
singleMovie: singleMovie
});
}catch(err){
console.error(err.message);
}
});
Also make sure you are using nodejs -v 8+ and mongoose -v 5+
I'm using node and postgres, I'm new to writing async function, what I'm trying to do is a very simple query that will do a total count of records in the database, add one to it and return the result. The result will be visible before the DOM is generated. I don't know how to do this, since async function doesn't return value to callers (also probably I still have the synchronous mindset). Here's the function:
function generateRTA(callback){
var current_year = new Date().getFullYear();
const qry = `SELECT COUNT(date_part('year', updated_on))
FROM recruitment_process
WHERE date_part('year', updated_on) = $1;`
const value = [current_year]
pool.query(qry, value, (err, res) => {
if (err) {
console.log(err.stack)
} else {
var count = parseInt(res.rows[0].count) + 1
var rta_no = String(current_year) + '-' + count
callback(null, rta_no)
}
})
}
For the front-end I'm using pug with simple HTML form.
const rta_no = generateRTA(function (err, res){
if(err){
console.log(err)
}
else{
console.log(res)
}
})
app.get('/new_application', function(req, res){
res.render('new_application', {rta_number: rta_no})
});
I can see the rta_no in console.log but how do I pass it back to the DOM when the value is ready?
Based on the ajax call async response, it will update the div id "div1" when it gets the response from the Node js .
app.js
app.get("/webform", (req, res) => {
res.render("webform", {
title: "Render Web Form"
});
});
app.get("/new_application", (req, res) => {
// Connect to database.
var connection = getMySQLConnection();
connection.connect();
// Do the query to get data.
connection.query('SELECT count(1) as cnt FROM test ', function(err, rows, fields) {
var person;
if (err) {
res.status(500).json({"status_code": 500,"status_message": "internal server error"});
} else {
// Check if the result is found or not
if(rows.length==1) {
res.status(200).json({"count": rows[0].cnt});
} else {
// render not found page
res.status(404).json({"status_code":404, "status_message": "Not found"});
}
}
});
// Close connection
connection.end();
});
webform.pug - Via asynchronous call
html
head
script(src='https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js')
script.
$(document).ready(function(){
$.ajax({url: "/new_application", success: function(result){
$("#div1").html(result.count);
}});
});
body
div
Total count goes here :
#div1
value loading ...
That seems okay, I'm just not sure of this:
The result will be visible before the DOM is generated
This constraint defeats the purpose of async, as your DOM should wait for the returned value to be there. Instead of waiting for it you could just render the page and once the function returns and runs your callback update the value.
Also, perhaps it's worth having a look into promises