Set object in SequelizeJS function - node.js

I'd like to get all my projects in the findAll() function of SequelizeJS but it seem's not working outside the function...
var myProjects;
Project.findAll().then(function(projects) {
myProjects = projects;
});
console.log(myProjects); // it doesn't work
EDIT #2
I'm trying to create an object containing all my links that I can get on each views without calling findAll() on each actions... projects was an example, but the real context is on my link's model !
var dbContext = require('./../../db/DbContext');
var _ = require('lodash');
var LinkDao = function () {
this.context = dbContext.entities;
};
_.extend(LinkDao.prototype, {
getAllByOrder: function (callback) {
return this.context.Link.findAll({order: 'position ASC', include: [{ model: this.context.Link}], where: {type: [0,1]}});
},
});
module.exports = LinkDao;
exports.locals = function(app){
app.use(function(request, response, next){
var linkDao = new LinkDao();
linkDao.getAllByOrder().success( function(links){
response.locals.navLinks = links;
});
var ecCategoryDao = new EcCategoryDao();
ecCategoryDao.getAll().success( function(ecCategories) {
response.locals.ecCategories = ecCategories;
next(); // navLinks is not accessible
});
});
};
<% navLinks.forEach(function(link){ %>
<% if(link.type === 0) { %>
<li><%-link.name%></li>
<li class="top-bar-divider"></li>
<% } else { %>
<li><%-link.name%></li>
<li class="top-bar-divider"></li>
<% } %>
<% }); %>

Related

Getting "TypeError: Cannot read properties of null (reading 'items')" error but the code works after reloading

so I was working on making this Todo list website but I am facing a problem.
NODE.JS CODE:
//jshint esversion:6
// _______________________________Database Code_________________________________
const mongoose = require("mongoose")
none = []
main().catch(err => console.log(err));
async function main() {
mongoose.set('strictQuery', false);
await mongoose.connect('mongodb://0.0.0.0:27017/todolistDB');
}
// For the main list
const itemSchema = {
itemName: {
type: String,
required: true
}
}
const Item = mongoose.model("Item", itemSchema)
const buyFood = new Item({
itemName: "Buy Food"
})
const cookFood = new Item({
itemName: "Cook Food"
})
const eatFood = new Item({
itemName: "Eat Food"
})
const defaultItems = [buyFood, cookFood, eatFood]
// New list schema
const listSchema = {
listName: String,
items: [itemSchema]
}
const List = mongoose.model("list", listSchema)
// Function that creates new lists
function makeNewList(name) {
const list = new List({
listName: name,
items: defaultItems
})
list.save()
}
// Function that creates new list items
function createNewItem(newItem) {
const item = new Item ({
itemName: newItem
})
}
// Function to find a list
function findList(listName) {
List.findOne({listName: listName}, function(err, list) {
if (!err) {
return list
}
})
}
// _______________________________Server Code___________________________________
const express = require("express");
const bodyParser = require("body-parser");
const date = require(__dirname + "/date.js");
const _ = require("lodash")
const popup = require("node-popup")
const app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));
const workItems = [];
// Default Home List
app.get("/", function(req, res) {
const day = date.getDate();
Item.find(function(err, item) {
if (item.length === 0) {
Item.insertMany(defaultItems, function(err) {
if (err) {
console.log(err);
} else {
console.log("Items added successfully.");
}
})
}
else if (err) {
console.log(err);
}
else {
List.find({}, function(err, list) {
if (err) {
console.log(err);
}
else if (list.length === 0) {
res.render("list", {listTitle: day, newListItems: item, array: none});
}
else {
list.forEach(function(listName) {
console.log(listName);
})
res.render("list", {array: list, newListItems: defaultItems, listTitle: day})
}
})
}
})
});
// Creating new list items
app.post("/", function(req, res){
const item = req.body.newItem;
const listName = req.body.list;
if (listName === "day") {
createNewItem(item)
res.redirect("/")
}
// else {
// List.findOne({listName: listName}, function(err, foundList) {
// foundList.items.push(item)
// foundList.save()
// res.redirect("/" + listName)
// })
// }
});
// Deleting list items
app.post("/delete", function(req, res) {
deletedItem = String(req.body.box)
Item.deleteOne({_id: deletedItem}, function(err) {
if (err) {
console.log(err);
} else {
console.log("Item deleted successfully");
}
})
res.redirect("/")
})
// Making new lists
app.post("/list", function(req, res) {
newList = req.body.newListName.toLowerCase()
List.findOne({listName: newList}, function(err, listInSearch) {
if (!listInSearch) {
console.log("Does not exist");
makeNewList(newList)
res.redirect("/" + newList)
}
else {
console.log("Exist");
}
})
})
// Loading existing list
app.get("/:extension", function(req, res) {
extension = req.params.extension.toLowerCase()
console.log("Site ends with " + extension);
if (extension !== "list") {
List.find({}, function(err, list) {
if (err) {
console.log(err);
}
else {
List.findOne({listName: extension}, function(err, foundList) {
if (!err) {
items = foundList.items
console.log(items);
res.render("list", {array: list, newListItems: foundList.items, listTitle: _.startCase(extension)})
}
})
}
})
}
})
// app.post("/:extension", function(req, res) {
// extension = req.params.extension.toLowerCase()
// item = req.body.newItem.toString()
//
// console.log(item);
// console.log(extension);
//
// List.findOne({listName: extension}, function(err, foundList) {
// if (!err) {
// createNewItem(item)
// foundList.items.push(item)
// foundList.save()
// res.redirect("/" + extension)
// }
// })
// })
// About page
app.get("/about", function(req, res){
res.render("about");
});
// Server port
app.listen(2000, function() {
console.log("Server started on port 2000");
});
HTML CODE:
<%- include("header") -%>
<!-- Showing list title -->
<div class="content">
<div class="box" id="heading">
<h1> <%= listTitle %> </h1>
</div>
<!-- Showing all lists -->
<div class="form">
<div class="btn-group">
<button type="button" class="btn btn-danger dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
Lists
</button>
<ul class="dropdown-menu">
<% array.forEach(function(item) {%>
<li><a class="dropdown-item" href="/<%= item.listName %>"> <%= item.listName %> </a></li>
<% }) %>
<li><hr class="dropdown-divider"></li>
<li><a class="dropdown-item" href="/">Default List</a></li>
</ul>
</div>
<!-- Making new lists -->
<div class="list drop">
<form action="/list" method="post">
<input type="text" name="newListName" placeholder="New List Name" autocomplete="off">
<button class="btn btn-primary btn-md" type="submit" name="newList">Create</button>
</form>
</div>
</div>
<!-- Showing each list item -->
<div class="box">
<% newListItems.forEach(function(item) {%>
<form class="form-group" action="/delete" method="post">
<div class="item">
<input type="checkbox" onChange="this.form.submit()" name="box" value="<%= item._id %>">
<p><%= item.itemName %></p>
</div>
</form>
<% }) %>
<!-- Adding new list items -->
<form class="item" action="/" method="post">
<input type="text" name="newItem" placeholder="New Item" autocomplete="off">
<button class="button" type="submit" name="list" value="<%= listTitle %>">+</button>
</form>
</div>
</div>
<%- include("footer") -%>
Now, the website works well for the home page but I have added the functionality to make custom lists with custom names and that's where the issue arises. Whenever I make a new list, I want to add some items to it that are then stored in mongodb database. But if you look at the "Loading existing list" section of the .js code, there's the "newListItems" parameter which is supposed to take a list of items which are later displayed on the screen using a forEach() loop in the html document using EJS. Now, I have checked it multiple times, the items always get added to the database and exist there but when it's time to render them, the "foundList.items" gives that "TypeError: Cannot read properties of null (reading 'items')" error. I don't know what to do... And one more thing, when I try to create a new list after already creating one before, the second one doesn't gets any issues whatsoever. No idea what that is but it only happens the first time.
I hope someone can help...

How to implement pagination with mongoose and EJS and keep the search query when paging?

Im using Nodejs, EJS, Mongoose and MongoDB and i have a table that is created from the documents in my DB and cant get paging buttons to work without clearing my search query.
The way my app works is
Click on the search link which opens a search filter page.
My Search page
Then you select you filer and search. Results are then shown. With Search Query in URL
Searched Results with Search Query
3.When you click on the next page it clears your query.
Page buttons
Here is my paging buttons and below is my route
My search filters are on another page.
<div class="container">
<nav aria-label="...">
<ul class="pagination float-right">
<li class="page-item disabled">
<span class="page-link">Previous</span>
</li>
<li class="page-item active">
<a class="page-link" name="1" href="/searched/1">1</a>
</li>
<li class="page-item">
<a class="page-link" name="2" href="/searched/2">2</a>
</li>
<li class="page-item">
<a class="page-link" name="3" href="/searched/3">3</a>
</li>
<li class="page-item">
<a class="page-link">Next</a>
</li>
</ul>
</nav>
</div>
app.get("/searched/:page/:limit", function (req, res) {
if (req.isAuthenticated()) {
// const { page, limit } = req.params;
// const options = {
// sort: { dateAdded: -1 },
// page: page,
// limit: limit,
// };
const query = req.query;
if (query.btu === "") {
delete query.btu;
}
if (query.sn1 === "") {
delete query.sn1;
}
if (query.sn2 === "") {
delete query.sn2;
}
if (query.userCreated === "") {
delete query.userCreated;
}
if (query.split === "") {
delete query.split;
}
if (query.supplier === "") {
delete query.supplier;
}
if (query.issued === "") {
delete query.issued;
}
// Aircon.paginate(query, options, function (err, foundAircons) {
// if (err) {
// console.log(err);
// } else {
// console.log(foundAircons);
// res.render("instock", {
// foundAircons: foundAircons.docs,
// });
// }
// });
Aircon.find(query)
.sort({
dateAdded: "desc",
})
.exec((err, foundAircons) => {
if (err) {
console.log(err);
} else {
res.render("instock", {
foundAircons: foundAircons,
});
}
});
} else {
res.redirect("/login");
}
});
Actually, your structure looks unfamiliar to me. I'm not sure have you ever heard "pagination token" term. If you didn't you can check this magnificent guide.
I wrote searching endpoint with parameters like searchTerm, limit and pageToken to paginate. pageToken is important. If you want to go page: 2 for example. page token should be first record after the last record of the first page results. I used _id parameter in this example
Note: Creating index is mandatory for filter the records with searchTerm. Index creation is like this:
await db.collection(feedSettings._collection).createIndex({ "$**": "text" }, { name: "TextIndex" });
Code:
exports.pagination = async (req, res, next) => {
const db = await database.mongo;
const feedSettings = req.feedSettings;
// Query parameters
const limit = parseInt(req.query.limit) || 100;
let searchTerm = req.query.searchTerm;
let pageToken = req.query.pageToken;
const query = { _feedName: feedSettings.name };
// Start from last item
let paginatedQuery = {
_feedName: feedSettings.name,
_id: { $gt: ObjectID(pageToken) },
_trashed: { $ne: true }
}
// If we don't have a pageToken start from first item
if (!pageToken) {
let firstFeed = await db.collection(feedSettings._collection).findOne(query, { projection: { _id: 1 } });
if (!firstFeed) {
return res.status(200).json({
success: 1,
data: []
});
}
paginatedQuery._id = { $gte: ObjectID(firstFeed._id) };
}
// If user doesn't want to search a term in items
if (typeof searchTerm === 'string') {
await db.collection(feedSettings._collection).createIndex({ "$**": "text" }, { name: "TextIndex" });
paginatedQuery.$text = { $search: searchTerm };
}
feedsData = await db.collection(feedSettings._collection)
.find(paginatedQuery)
.limit(limit)
.toArray();
return res.status(200).json({
success: 1,
data: feedsData
});
}
managed to get it working as well with mongoose paginate v2 and found a function to rebuild the query string and pass back to the buttons
function objectToQueryString(obj) {
var str = [];
for (var p in obj)
if (obj.hasOwnProperty(p)) {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
}
return str.join("&");
}
app.get("/searched", function (req, res) {
if (req.isAuthenticated()) {
const { page } = req.query;
const options = {
sort: { dateAdded: -1 },
page: !page ? 1 : page,
limit: 20,
};
const query = req.query;
delete query.page;
if (query.btu === "") {
delete query.btu;
}
if (query.sn1 === "") {
delete query.sn1;
}
if (query.sn2 === "") {
delete query.sn2;
}
if (query.userCreated === "") {
delete query.userCreated;
}
if (query.split === "") {
delete query.split;
}
if (query.supplier === "") {
delete query.supplier;
}
if (query.issued === "") {
delete query.issued;
}
var queryString = objectToQueryString(query);
console.log(queryString);
Aircon.paginate(query, options, function (err, results) {
if (err) {
console.log(err);
} else {
res.render("instock", {
foundAircons: results.docs,
total: results.totalDocs,
hasPrev: results.hasPrevPage,
hasNext: results.hasNextPage,
pageCount: results.totalPages,
page: results.page,
url: queryString,
});
}
});
} else {
res.redirect("/login");
}
});
<div class="container">
<nav aria-label="...">
<ul class="pagination float-right">
<% let prev = "disabled"; if(hasPrev){ prev = "" }; %>
<li class="page-item <%= prev %>">
<a class="page-link" href="/searched/?<%= url %>&page=<%= page - 1 %>"
>Previous</a
>
</li>
<% for(let i = 1; i <= pageCount; i++){ %> <% let active = ""; %>
<%if(page === i) { active = "active"} %>
<li class="page-item <%= active %>">
<a class="page-link" name="1" href="/searched/?<%= url %>&page=<%= i %>"
><%= i %></a
>
</li>
<% }; %> <% let next = "disabled"; if(hasNext){ next = "" }; %>
<li class="page-item <%= next %>">
<a class="page-link" href="/searched/?<%= url %>&page=<%= page + 1 %>"
>Next</a
>
</li>
</ul>
</nav>
</div>

I want to display data in the result.ejs: What should i do

Here is my db.js:
const { Pool, Client } = require('pg');
const pool = new Pool({
user: "postgres",
host: "localhost",
database: "myfirst_postgres",
password: "qweqwe",
port: 5432
});
// ...
pool.query("SELECT * FROM members ",
(err, res) => {
console.log(err, res)
pool.end()
});
I want to require it in result.ejs
I wrote in result.ejs file like : <%= require ('/db.js')=%>
but after what should i write
Thanks in advance!
You can pass the results from your db-query to the ejs-template. Something like this (assuming you are using express):
Request-Handler:
app.get('/get-data', (req, res) => {
pool.query('SELECT * FROM members ', (err, res) => {
if (err) {
//handle error
}
pool.end();
res.render('result', { members: res.rows });
});
});
EJS-File result.ejs (in views folder):
<% if (members.length > 0) { %>
<div class="grid">
<% for(member of members) { %>
<p><%= member.firstName %></p>
<!-- and so on for other properties -->
<% } %>
</div>
<% } else { %>
<h3>No members found!</h3>
<% } %>

change link to logout when user login

I want to change login button to logout when ctx.session.userID have value, I try to use ejs engine, but it didn't work.
I use console.log to print userid after login, but it shows undefined on terminal even it being assigned value in login().
This is server.js:
const M = require('./model')
const Koa = require('koa')
var serve = require('koa-static')
const session = require('koa-session')
var KoaRouter = require('koa-router')
var koaLogger = require('koa-logger')
const koaBody = require('koa-body')
const views = require('koa-views')
var app = new Koa()
const router = new KoaRouter()
app.use(views('view', {map:{html:'ejs'}}))
app.use(koaLogger())
app.use(koaBody())
app.use(router.routes())
app.use(serve(__dirname + '/public'));
app.keys = ['*#&))9kdjafda;983']
const CONFIG = {
key: 'd**#&(_034k3q3&#^(!$!',
maxAge: 86400000
}
app.use(session(CONFIG, app))
router
.get('/', async (ctx) => {
let title = 'ejs test'
let userid = ctx.session.userID
console.log('ctx.session.userID:',userid) // print userid after login, but it shows undefined
await ctx.render('index',{
title, userid
})
})
.post('/login', login)
.get('/error', async (ctx)=> {
await ctx.render('error',{})
})
async function login(ctx){
let {id, password} = ctx.request.body
console.log("test:",id,password)
if ( await M.get(id,password) != null){
ctx.session.userID = id
ctx.redirect('/')
console.log('login success')
}
else {
ctx.redirect('/error')
}
}
And this is a part of index.html:
<% if (userid == null){ %>
Login
<% } else { %>
Logout
<% } %>
Hi If user is not logged in by default it will store undefined.
you need to check if user id is defined or not -
<% if (userid === undefined){ %>
Login
<% } else { %>
Logout
<% } %>
Hop this helps.

Data from mongodb not displaying in view using EJS

I'm using mongoose and express along with EJS. For some reason, data I have in my mongodb is not appearing in the view. I get no errors, it's just blank.
var Person = require('.././schema.js');
module.exports = function(app) {
app.get('/about', function(req, res) {
var peopleList = [];
var title = "Users in Database:";
Person.find(function (err, people) {
if (err) return console.error(err);
for(var i = 0; i < people.length; i++) {
peopleList.push({name: people[i].name, role: people[i].role, wage: people[i].wage});
}
console.log(peopleList);
console.log(peopleList[0].name + ' ' + peopleList[0].wage + ' ' + peopleList[0].role);
});
res.render('pages/about', {
peopleList: peopleList,
title: title
});
});
}
And in my view:
<h3><%= title %></h3>
<blockquote>
<ul>
<% for(var i = 0; i < peopleList.length; i++) { %>
<li><%= peopleList[i].name %> : <%= peopleList[i].role %> : <%= peoplelist[i].wage %></li>
<% }; %>
</ul>
Alternate attempt:
<ul>
<% peopleList.forEach(function(peopleList) { %>
<li><%= peopleList.name %> - <%= peopleList.role %></li>
<% }); %>
</ul>
<%= title %> works just fine, just not the data. If I create my own array with objects in it and use the same forEach loop, it also works.
var Person = require('.././schema.js');
module.exports = function(app) {
app.get('/about', function(req, res) {
var peopleList = [];
var title = "Users in Database:";
Person.find(function (err, people) {
if (err)
return console.error(err);
for(var i = 0; i < people.length; i++)
{
peopleList.push({name: people[i].name, role: people[i].role, wage: people[i].wage});
}
console.log(peopleList);
console.log(peopleList[0].name + ' ' + peopleList[0].wage + ' ' + peopleList[0].role);
res.render('pages/about', {
peopleList: peopleList,
title: title
});
});
});
}
Please change your code to this.
Note: you should put res.render in the callback function of Person.find.

Resources