I've captured data and display them by doing this:
const items = [];
Task.find({},(err,tasks)=>{
if(err){
console.log(err);
}else{
tasks.forEach((task)=>{
items.push(task.name);
})
}
})
app.get("/", (req, res) => {
today = date.getDate();
res.render('list', { kindOfDay: today, items: items });
})
But when I try to do this instead, it failed to display the data with out any error:
app.get("/", (req, res) => {
const items = [];
Task.find({}, (err, tasks) => {
if (err) {
console.log(err);
} else {
tasks.forEach((task) => {
items.push(task.name);
//console.log(task.name) still works
})
}
});
today = date.getDate();
res.render('list', { kindOfDay: today, items: items });
})
Does anybody knows why the code above refuse to display data when I render the 'list' page?
Thank you!
mongoose find method is asynchronous, res.render might/would execute before the array gets populated. your code should be as below
app.get("/", (req, res) => {
const items = [];
Task.find({}, (err, tasks) => {
if (err) {
console.log(err);
} else {
tasks.forEach((task) => {
items.push(task.name);
//console.log(task.name) still works
});
}
today = date.getDate();
res.render('list', { kindOfDay: today, items: items });
});
})
Related
Quick question: how can I sort my posts data by date?
router.get('/', async (req, res) => {
try {
const posts = await Post.find()
res.json(posts)
}
catch (err) {
res.json({message: err})
}
})
I came from Django and there you could do something like:
posts = Post.objects.filter().order_by('date')
I'm fairly new to NodeJS and Express. Thanks a lot!
It depends on the what the data structure of the date property is. If they are in JS timestamp format:-
router.get('/', async (req, res) => {
try {
const posts = await Post.find();
const sortedPosts = posts.sort((a,b) => {
return new Date(b.date) - new Date(a.date);
});
res.json(sortedPosts)
}
catch (err) {
res.json({message: err})
}
})
Here I've used the array's sort() method. Learn more
I am trying to get the ID of the document that I just inserted into mongoDB. Here is the node.js code:
app.post("/groups/new", (req, res) => {
const dbGroup = req.body;
Groups.create(dbGroup, (err) => {
if (err) {
res.status(500).send(err);
} else {
var id = dbGroup._id;
res.status(201).send(id);
}
});
});
I have tried various things, like adding a group to the function:
app.post("/groups/new", (req, res) => {
const dbGroup = req.body;
Groups.create(dbGroup, (err, group) => {
if (err) {
res.status(500).send(err);
} else {
var id = group._id;
res.status(201).send(id);
}
});
});
But that also does not work, so I tested if my even get the API response on the front end with:
res.status(201).send("test");
Which works perfectly fine. So I don't know why this doesn't work, because all the documentation says this is the way.
I figured a way to get the id. It may be not the most efficient way, because it sends all the data it gets but it gets the job done.
Backend:
app.post("/groups/new", (req, res) => {
const dbGroup = req.body;
Groups.create(dbGroup, (err, data) => {
if (err) {
res.status(500).send(err);
} else {
res.status(201).send(data);
}
});
});
Front end:
axios.post("/groups/new", {
groupname: roomName,
}).then((res) => {
roomid = res.data._id;
});
I'm really new to node/express/mongoDB coding, and I have a slight problem with adding/updating values into mongoDB via node/express.
app.post('/', (req, res, next) => {
let data = {
first_value: req.body.first_value,
second_value: req.body.second_value,
};
dbase.collection("testDB").insertOne(data, (err, result) => {
if (err) {
console.log(err);
}
res.send('data added successfully');
});
});
app.put('/:id', (req, res, next) => {
var id = { _id: new ObjectID(req.params.id) };
dbase.collection("testDB").updateOne({ _id: id }, {
$set: {
first_value: req.body.first_value
second_value: req.body.second_value,
}
}, (err, result) => {
if (err) {
throw err;
}
res.send('data updated sucessfully');
});
});
app.put does not alter the values in DB, and app.post only adds "null" into every section of the new entry when I'm trying them with Postman. When I add new values with html form, the data is added correctly.
What is the problem with my code?
For app.post , can you provide me a screen shot of the way you are entering data and in which format e.g. , application/raw , application/x-www-form-urlencoded etc .
For app.put you need to correct the following things . The corrected code is as below ,
app.put('/:id', (req, res, next) => {
var id = { _id: new ObjectID(req.params.id) };
dbase.collection("testDB").updateOne( id , { // put "id" instead of "{ _id: id }"
$set: {
first_value: req.body.first_value
second_value: req.body.second_value,
}
}, (err, result) => {
if (err) {
throw err;
}
res.send('data updated sucessfully');
});
});
Hope you can get the point and this works for you .
Hi friends I'm trying to find in my subDoc category string matching
Here is the code:
router.get('/:_categoryName', (req, res, next) => {
Malgezot.findOne({ 'items.category': req.params._categoryName }, (err, malgezot) => {
if(err) return res.render('body/category', {info: ''});
console.log(malgezot);
});
});
But the results is all of the items!
I also tried:
router.get('/:_categoryName', (req, res, next) => {
Malgezot.find({'items': { 'category': req.params.categoryName }}, (err, malgezot) => {
if(err) return res.render('body/category', {info: ''});
console.log(malgezot);
});
});
If your data is in form of object then query should be :
router.get('/:_categoryName', (req, res) => {
const { _categoryName } = req.params;
Malgezot.findOne({
'items.category': _categoryName
}).then((data) => {
if (data) {
res.status(200).json(data)
}
}).catch((err) => {
res.status(500).json({
message: 'Internal server error'
});
});
});
Or if your data in form of array then your query should be:
router.get('/:_categoryName', (req, res) => {
const { _categoryName } = req.params;
Malgezot.findOne({
item : { $in : [{ category: _categoryName }] }
}).then((data) => {
if (data) {
res.status(200).json(data)
}
}).catch((err) => {
res.status(500).json({
message: 'Internal server error'
});
});
});
I need to render view after mongodb provide data from database. I write this code but the main problem is view is generated before getting data.
router.get('/', async(req, res, next)=> {
try{
const products = await Product.find({});
res.render('shop/index', { title: 'Express',products });
}catch(e){
console.log(e);
}
});
You could try doing something like this:
router.get("/", async (req, res, next) => {
Product.find({}, (err, items) => {
if (err) {
console.log(err);
res.status(500).send("An error occurred", err);
} else {
res.render("home", { items });
}
});
});
Actually everything looks great, idk why it's not working. I probably write something like this:
router.get("/", async (req, res) => {
const products = await Product.find({});
if (!products) return res.render("error");
res.render("shop/index", {
title: "Express",
products
});
});