Compile two different mongodb entries - javascript

I am just starting with javascript / express / mongodb. As a little starting project I want to do a simple task manager. The todos should be divided by prios. So every entry has it's flag "high", "mid" or "low".
However, I can't manage to show the different entries on the index page.
The error message is: "tasks_low is not defined"
This is the relevant js snippet:
app.get('/', function(req, res){
db.tasks.find({prio: 'high'}, function (err, highs) {
res.render('index', {
title: 'Aufgaben High:',
tasks: highs
});
})
});
app.get('/', function(req, res){
db.tasks.find({prio: 'low'}, function (err, lows) {
res.render('index', {
title: 'Aufgaben Low:',
tasks_low: lows
});
})
});
This is my index.ejs file:
<h1>Prio High</h1>
<ul>
<% tasks.forEach(function(tasks){ %>
<li><%= tasks.task %> <%= tasks.prio %> - <a class="deleteUser" data-id="<%= tasks._id %>" href="#">x</a></li>
<% }) %>
</ul>
<br><br>
<h1>Prio Low</h1>
<ul>
<% tasks_low.forEach(function(tasks_low){ %>
<li><%= tasks_low.task %> <%= tasks_low.prio %> - <a class="deleteUser" data-id="<%= tasks_low._id %>" href="#">x</a></li>
<% }) %>
</ul>
However, when I compile to different views it all works well!
app.get('/tasks_high/', function(req, res){
db.tasks.find({prio: 'high'}, function (err, highs) {
res.render('index', {
title: 'Aufgaben High:',
tasks: highs
});
})
});
app.get('/tasks_low/', function(req, res){
db.tasks.find({prio: 'low'}, function (err, lows) {
res.render('index', {
title: 'Aufgaben Low:',
tasks_low: lows
});
})
});

Just create a collection entry with title + task:
// Task collection structure
var Task= mongoose.model('Tasks', {
title: String,
priority: String,
});
And then filter each task based in its priority as you're doing, but using the same collection

Related

?_method=DELETE is not working in this CRUD app. I am following Colt Steele's Full stack bootcamp

const methodOverride = require("method-override");
app.use(methodOverride("_method"));
app.delete("/comments/:id", (req, res) => {
const { id } = req.params;
comments = comments.filter((c) => c.id !== id);
res.redirect("/comments");
});
<h1>Comment id: <%= comment.id %></h1>
<h2><%= comment.comment %> - <%=comment.username %></h2>
Back to index
Edit Comment
Edit Comment
<form method="POST" action="/comments/ <%= comment.id %>?_method=DELETE">
<button>Delete</button>
</form>
Building a simple CRUD app and the ?_method=DELETE is not working for some reason. I am able to do everything else, however when I try to delete there is no error. The page just redirects/refreshes. Any help would be appreciated.

errorMessage is not defined

How do I use errorMessage object from routes in a partial.I tried this
Route:-
const express = require("express");
const router = express.Router();
const Character = require("../models/character");
// All Character
router.get("/", (req, res) => {
res.render("characters/index");
});
// New Character
router.get("/new", (req, res) => {
res.render("characters/new", { character: new Character() });
});
// Creat
router.post("/", (req, res) => {
const character = new Character({
name: req.body.name,
});
character.save((err, newCharacter) => {
if (err) {
res.render("characters/new", {
character: character,
errorMessage: "Error Creating",
});
} else {
// res.redirect(`characters/${newCharacter.id}`)
res.redirect("characters");
}
});
});
module.exports = router;
layout:-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Test</title>
</head>
<body>
<%- include("../views/partials/header.ejs") %>
<%- include("../views/partials/errorMessage.ejs") %>
<br />
<%- body %>
<br />
</body>
</html>
partial :-
<%= errorMessage %>
it gives me this error:-
ReferenceError: D:\Web_Development\LGS\layouts\layout.ejs:10
8|
9| <body>
>> 10| <%- include("../views/partials/header.ejs") %> <%-
11| include("../views/partials/errorMessage.ejs") %>
12| <br />
13| <%- body %>
D:\Web_Development\LGS\views\partials\errorMessage.ejs:1
>> 1| <%= errorMessage %>
2|
errorMessage is not defined
Maybe should you try to include specifix variables :
<%- include("../views/partials/errorMessage.ejs", {errorMessage}) %>
Or just check the avaibality of your variable as it's in the main layout...
<% if (errorMessage !== undefined) { %>
<%= errorMessage %>
<% } %>
You are passing data from sever to "characters/new.ejs" this file
and now in new.ejs file you have used layouts such as header and errorMessage by using <%- include() %> statement
and to pass data from new.ejs file to this layouts you need to provide second argument to <%- include() %> statement and object of data that you want to pass
so in your example to pass errorMessage to
"../views/partials/errorMessage.ejs" you need to provide
<%- include("../views/partials/errorMessage.ejs", {errorMessage}) %>
then you can use this passed data to your layout like <%= errorMessage %>
if you want to pass more then one data you can do this
<%- include("../views/partials/errorMessage.ejs", {data1, data2, ...}) %>
try this it might be helpful it worked for me !!!!!
<% if(locals.errorMessage != null) {%>
<%= errorMessage %>
<%}%>
I had the same problem... and I solved it by using this:
<%= locals.errorMessage %>

can't fetch data from mongodb and display that into html

model named Field.js
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/SuperchainV1', {
useNewUrlParser: true });
mongoose.set('useNewUrlParser', true);
mongoose.set('useFindAndModify', false);
mongoose.set('useCreateIndex', true);
const db = mongoose.connection;
const FieldSchema = mongoose.Schema({
productID: {
type: String
},
productName:{
type: String
},
fieldLocation: {
type: String
},
farmerName: {
type: String
},
farmerMobile: {
type: String
},
farmerNid: {
type: String
},
date: {
type: Date,
default: Date.now
}
});
const Field = mongoose.model('Field', FieldSchema);
module.exports = Field;
routes index.js
router.get('/dashboard', ensureAuthenticated, (req, res) => {
let field = Field.find({})
.sort({date:'desc'}).exec( (err, field) => {
res.render('dashboard', field);
});
})
dashboard.ejs where i want to display data after fetching
<div class="jumbotron">
<p class="lead">
<% field.productID %>
<% field.productName %>
<% field.fieldLocation %>
<% field.farmerName %>
<% field.farmerNumber %>
<% field.farmerNid %>
</p>
</div>
errors i get "field is not defined"
I want to fetch data from collections fields and display all the data into a ejs page named dashboard i tried this but always get the error field is not defined.
You need to use for loop in ejs template
<% for(var i=0; i < field.length; i++) { %>
<div class="jumbotron">
<p class="lead">
<%= field[i].productID %>
<%= field[i].productName %>
<%= field[i].fieldLocation %>
<%= field[i].farmerName %>
<%= field[i].farmerNumber %>
<%= field[i].farmerNid %>
</p>
</div>
<% } %>

Can't get username from req.user to output in express

I'm using ejs to try to output a username from req.user in a node express app, but it doesn't seem to be working.
This is where my username and password come in:
app.get('/', function(req, res) {
res.render('index', {
isAuthenticated: req.isAuthenticated(),
user: req.user
});
console.log("req.user:", req.user);
});
At this point, I can see req.user in terminal displayed like this:
req.user: [ { _id: 5890f8a97ef995525d4b78cd,
username: 'dave',
password: 'somepassword',
__v: 0 } ]
This is what I have in index.ejs:
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
<head>
<body>
<% if (!isAuthenticated) { %>
Log in here
<% } else { %>
Hello, <%= user.username %>!
Log out
<% } %>
</body>
</html>
And this is the login form:
<!DOCTYPE html>
<html>
<head>
<title>Passport</title>
<head>
<body>
<form action="" method="post">
<input type="text" name="username" placeholder="Username">
<input type="password" name="password" placeholder="Password">
<input type="submit" value="Login">
</form>
</body>
</html>
I initially had this in my index.ejs, but still did not output username.
Hello, <%= user.name %>!
Would appreciate any help.
Based on what your terminal displayed, it looks like req.user is an array containing objects, which means that you would need to access one of the elements in the array before accessing the object's properties.
Therefore <%= user.username %> would be <%= user[0].username %>:
<% if (!isAuthenticated) { %>
Log in here
<% } else { %>
Hello, <%= user[0].username %>!
Log out
<% } %>
Or you could just update the web service to pass in the first element in the user array:
res.render('index', {
isAuthenticated: req.isAuthenticated(),
user: req.user[0]
});
<% if (!isAuthenticated) { %>
Log in here
<% } else { %>
Hello, <%= user.username %>!
Log out
<% } %>
You may also want to check if the user array contains any elements to prevent any errors from being thrown if it doesn't:
res.render('index', {
isAuthenticated: req.isAuthenticated(),
user: (req.user && req.user.length) ? req.user[0] : {}
});

Using remote: true from .js file

This is almost an identical question as was asked here: https://stackoverflow.com/questions/28571985/rails-remote-true-equivalent, but no one answered. I am hoping this doesn't mean that the question is impossible, though.
I have a page where a list of people can be dragged and dropped into bins. An assignment in a join table is automatically generated when they are dropped. I want the page to not re-load, though. In ruby, I would do this using remote: true, but the re-direct here happens in my javascript file. I believe everything is set up correctly, if only I could put remote: true at the end of my window.location.pathname line in the .js file.
z_game_sessions.js
app.gameSession = {
dragDrop: function () {
$('.groups-students').sortable({
tolerance:"pointer",
revert: true
});
$('.draggables').draggable({
connectToSortable: '.groups-students',
revert: 'invalid',
stop: function (e) {
var id = e.target.id;
var groupId = $(this).closest('ul').attr('id');
if (groupId) {
window.location.pathname = "game_sessions/add_player/" + groupId + "/" + id;
}
}
});
}
}
game_sessions_controller.rb
def add_player
#game_session = Group.find(params[:group_id]).game_session
GroupAssignment.assign(params[:group_id], params[:student_id], #game_session.id)
respond_to do |format|
format.js
end
end
add_player.js.erb
$("#new-group-form-container").html("<%= j(render partial: 'new_group_form', locals: {f: #game_session}) %>");
_new_group_form.html.erb
<%= f.simple_fields_for :groups do |ff| %>
<div class="mdl-cell mdl-cell--4-col mdl-shadow--4dp group-assignment-forms" id="group<%= "#{ff.object.id}" %>">
<h3>Group</h3>
Password: <%= ff.object.password %>
<%= ff.input :name, label: "Group Name", wrapper_html: { class: "mdl-textfield mdl-js-textfield mdl-textfield--floating-label" }, input_html: { class: "mdl-textfield__input" }, label_html: { class: "mdl-textfield__label" } %>
<%= ff.input :_destroy, as: :boolean, label: "Remove Group" %>
<h4>Students</h4>
<ul class="groups-students student-drag-area" id="<%= "#{ff.object.id}" %>">
<% ff.object.students.each do |student| %>
<li class="draggables" id="<%= student.id %>"><%= student.full_name %></li>
<% end %>
</ul>
</div>
<% end %>
First, it should be a POST request. Change your routes.
Second, make your controller return html and then just do an ajax request&assign that retuned html on success.
So instead of:
window.location.pathname = "game_sessions/add_player/" + groupId + "/" + id;
it should be something like:
$.ajax({
url: "game_sessions/add_player/" + groupId + "/" + id,
type: "POST",
success: function(data) {
$("#new-group-form-container").html(data)
}
});

Categories

Resources