How to retrieve data from mongodb and display in ejs page? - node.js

I have already added data to mongodb. I am using mongoose. I want to get data from mongodb database and display that in ejs page. I have searched a lot in the internet but I am getting errors while trying those. I do not understand what the error is. This is what I recently tried.
Mongoose schema
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var UserSchema = new Schema({
username:String,
_id:String,
dateOfBirth:Date,
telephoneNo:Number,
address:String,
email:String,
fb_Id:String,
jobTitle:String,
password:String
});
module.exports=mongoose.model('User',UserSchema);
Where I get data from mongodb
router.get('/', function(req, res){
user.find({}, function(err, profile){
res.render('AdminDatabase', { profile : profile});
});
});
Where I display in the ejs page
<div>
<ul>
<% for(var i=0; i<profile.length; i++) {%>
<li><%= profile[i].username %></li>
<li><%= profile[i]._id %></li>
<li><%= profile[i].dateOfBirth %></li>
<li><%= profile[i].telephoneNo %></li>
<li><%= profile[i].address %></li>
<li><%= profile[i].email %></li>
<li><%= profile[i].fb_Id %></li>
<li><%= profile[i].jobTitle %></li>
<% } %>
</ul>
</div>
But When I refresh the AdminDatabase page I get the error saying
ReferenceError: E:/Software project/Project/myProject/views/AdminDatabase.ejs:67
profile is not defined

Doesn't 'User' get turned into 'users', so the find code should look like
users.find({}...
..?

Related

Adding a Comment to a Post without refreshing the page (like Instagram) Node.js, Express, Mongoose

I am trying to make a Instagram-like website and trying to add a comment to a post without refreshing the whole page, I am working with Node.js, Express, Mongoose. I am fairly new and I checked other similar questions but havent found anything that covered this very topic using the express framework.
I would be very thankful for your help!
Some of my code:
//Sending all the posts and their comments to the homepage
app.get("/", async function(req,res){
//get all posts from db
//this also somehow includes all the comments
const allPosts = await posts.find({}).populate('comments');
res.render("home", {posts: allPosts});
});
//comments being displayed under the image
<div class="container">
<h5 class="card-title"></h5>
<p class="card-text"><%= posts.description %></p>
<% posts.comments.forEach(function(posts){ %>
<p><strong><%= posts.comment.author %> - </strong><%= posts.comment.text %></p>
<% }) %>
</div>
//post Schema
var postSchema = new mongoose.Schema({
image: String,
description: String,
comments: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Comment"
}
]
});

how to get an image from a folder to get to render in ejs

i am making an e-commerce website. currently, we are uploading an image using multer and rest of the data is getting saved in mongodb. all the data is getting upload correctly but when I try to get image from folder/public/image nothings work. any help would be appreciated.
this is my code for multer
app.post('/addProduct', function(req, res){
upload(req,res,(err)=>{
if(err){
res.render('addproduct',{
mesg: err
});
}
new product({
_id: new mongoose.Types.ObjectId(),
image:req.body.image,
name: req.body.name,
price: req.body.price,
description: req.body.description,
category: req.body.category,
}).save(function(err)
{
if(err){
console.log(err);
res.render('addProduct')
}else{
res.redirect('/products');
}
})
});
})
//all function for uploading images and checking file
//storage engine
const storage= multer.diskStorage({
destination: './Public/images/',
filename: function(req, file, cb){
cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
}
});
//upload method
const upload = multer({
storage: storage
}).single('image');
};
This is code for getting a file from ./public/image folder
<div class= "two row">
<% products.forEach(product => { %>
<div class="column">
<img src="./Public/images/<%req.files[0].filename%>" class="cover-img">
<p><%= product.name %></p>
<h3>&dollar;<%= product.price %></h3>
<!--- <p><%= product.description %></p>-->
</div>
<% }); %>
addProduct.ejs code
<div class= "two row" onclick="">
<% products.forEach(product => { %>
<div class="column">
<img src="/images/<%req.files[0].filename%>" class="cover-img">
<p><%= product.name %></p>
<h3>&dollar;<%= product.price %></h3>
<a action="/products/productId"></a><button class="btn">Add to cart</button></a>
<!--- <p><%= product.description %></p>-->
</div>
<% }); %>
I don't think that you need to have Public prepended to the asset path. So your <img> src can just be:
<img src="/images/<%req.files[0].filename%>" class="cover-img">
However, it's important that you have static assets set up for your Express application. Follow the docs here to see how that's done.
All you really need to do for that is to have:
app.use(express.static('Public'))
somewhere at the top of your Express app.

if statments are not working with ejs view engine

I'm trying to do "Orders page" that has a list of orders in a single page, but it should have seperate sections. One is for "Already made" and the other is for "Pending". It has a simple database with a field "isDone" that is either true or false. So as I imagine, if it is true, then it should appear on "Already made" section, but the problem is, that if statment doesn't work for some reason in .ejs.
<body class="container">
<main>
<div class="jumbotron">
<h1>Pending</h1>
</div>
<% orders_list.forEach(function(order){ %>
<% if(order.isDone == false) { %>
<div>
<h3><a href='<%= order.url %>'><%= order.name %></a> - <%= order.price %> euru</h3>
<hr>
</div>
<% } %>
<% }) %>
<div class="jumbotron">
<h1>Already made</h1>
</div>
<% orders_list.forEach(function(order){ %>
<% if(order.isDone == true) { %>
<div>
<h3><a href='<%= order.url %>'><%= order.name %></a> - <%= order.price %> euru</h3>
<hr>
</div>
<% } %>
<% }) %>
</main>
</body>
var express = require('express');
var router = express.Router();
var Order = require('../models/order');
router.get('/orders', function(req, res){
Order.find({})
.exec(function(err, list_orders){
if (err) {return next(err)};
// If Successful
res.render('../views/pages/index', {orders_list : list_orders});
});
});
module.exports = router;
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var OrderSchema = new Schema(
{
isDone: {type: Boolean, required: true},
name: {type: String, required: true},
quantity: {type: Number, required: true},
price: {type: Number, required: true},
phone: {type: Number},
});
OrderSchema
.virtual('url')
.get(function(){
return '/order/' + this._id;
});
module.exports = mongoose.model ('Order', OrderSchema);
I expect 'isDone' == true orders to go to 'Already made' section, and 'isDone' == false orders should go to the 'Pending' section. But not even single item appears. Database is connected successfully, if there are no if statments then orders appear on the page.
In your if condition you have quote your true value because ejs file is taking it as a value instead of a boolean value , so quote your true like this and it will work fine.
<% if(orders_list[i].isDone == 'true'){ %>
<div>
<h3><a href='<%= orders_list[i].url %>'><%= orders_list[i].name %></a> - <%= orders_list[i].price %> euru</h3>
<hr>
</div>
<% } %>

how to access the object in ejs

IMAGEThis is how ist's displayed on the web
I want to access the object part to display the data using EJS. I have failed to reach the object data.
My Schema
let Subject = mongoose.Schema({
name:[],
crh:[]
});
let Program = mongoose.Schema({
name: String,
semester: Number,
subject:[Subject]
});
let School = mongoose.Schema({
name:{
type: String,
},
program:[Program]
})
POST METHOD TO ACCESS THE DATE FROM THE DB
router.post('/view',(req,res) =>{
let school = req.body.school;
let semester = req.body.semester;
let program = req.body.program;
All.find({name:school,"program.name":program,"program.semester":semester},(err,record) =>{
if(err) throw err;
if(!record){
req.flash("error","We couldn't find any relevant document! ");
res.redirect('/admin/view');
}
if(record){
console.log(record);
res.render("./admin/viewSub",{find:record});
}
})
})
Consoled data! How do i access the data of the object from ejs. I want to display the data inside the object in table. I just want to know how to access it, when i try to use "." to reach the points; i am unable to reach the data.
[ { program: [ [Object] ],
_id: 5a9045474b530750a4e93338,
name: 'sose',
__v: 0 } ]
Try this.
<ul>
<li><%= find.name %></li>
</ul>
<ul>
<%for (var prog in find.program){%> //to fetch data from array of array
<li><%= prog.name %></li>
<li><%= prog.semester %></li>
<ul>
<% for (var sub in prog.subject){%>
<li><%= sub %></li>
<%}%>
</ul>
<%}%>
</ul>

How to use route parameters with Express

I'm having difficulty connecting the dots with the router.params objects with express.
Right now I'd like to have the button-success button in the code below point to a url that reads someaddress.com/formula/:item._id
HTML: (EJS Templating Engine)
<% formulas.forEach(function(item){ %>
<div class="pure-u-1 pure-u-sm-1-2 pure-u-md-1-4 pure-u-xl-1-5">
<div class="formula-block centered" id="<%= item._id %>">
<h4 class="padded-top"> <%= item.name %></h4>
<p> <%= item.description %></p>
<button class="button-success pure-button">Show</button>
<button class="button-warning pure-button">Delete</button>
</div>
</div>
<% }); %>
I am pairing that with this Express route:
router.get('/formula/:id', function(req, res){
var db = req.db;
var collection = db.get('formulas');
var id = req.params.id;
collection.find({"_id": id}, {}, function(e, doc){
res.render('formula/:id', {
formula: doc,
title: `formula for ${doc.name}`,
description: `modify and view ${doc.name} formula`
});
});
});
which then uses the information from the MongoDB document to generate the page.
It's not clear to me how you do this from looking at the documentation.
Thank you for your help.

Resources