Provide access to MongoDB data in a route quickly

I'm facing what appears to be a simple issue, yet struggling to locate comprehensive documentation on it. My goal is to pass JSON data from mongodb into a route for it to be accessible in my ejs template.

Here is my schema:

var GiveSchema   = new Schema({
    title: String,
    shortname: String,
    contents: String,
    image: String,
    category: String
});

module.exports = mongoose.model('GiveData',  GiveSchema);

var Givedata = mongoose.model( 'GiveData' );

To achieve this, I want to make the data available as the variable 'list' in the following route:

app.get('/', function(req, res) {
    res.render('index.ejs',{
      list: Givedata,
      bootstrappedUser: req.user,
      page: 'home'
    });
});

Answer №1

In order to retrieve your items, you will still have to make a database query.

app.get('/', function(req, res, next) {       
   ItemData.find(function(err, items){
     if(err) { return next(err); }
     res.render('index.ejs',{
       list: items,
       bootstrappedUser: req.user,
       page: 'home'
     });
  });
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Extract the content of a file in Node.js by reading it line by line until the end

I'm currently working on a project that involves using nodejs to read a file line by line and then converting the result into a JSON string. However, I've encountered an issue where the console.log returns undefined instead of the expected list. ...

creating a while loop in node.js

In C#, the following code would be used: double progress = 0; while (progress < 100) { var result = await PerformAsync(); progress = result.Progress; await Task.Delay(); } This concise piece of code spans just 7 lines. Now, how can we ...

Tips for ensuring that req.query only accepts date formats in the format yyyy-mm-dd

Can someone help me figure out how to restrict my req.query so that it only accepts dates in the format YYYY-MM-DD? Right now, my code is allowing random numbers like "123456" to be entered into the query. ...

What is the proper way to structure the DATETIME format when making an API request to mySQL?

Frontend code: import React, { Component, useState, useEffect } from "react"; import Navbar from "../Navbar/Navbar.js"; import BarChart from "../BarChart/BarChart"; ... Backend code: //set up express server const express = require("express"); const app ...

Acquire Category Permissions when making a channel in discord.js v14

I am in the process of setting up a channel that will grant specific roles access while automatically blocking out @everyone. I also want this setup to be compatible with categories, allowing for other roles to have permissions within them. let customPermi ...

Unexpectedly, Sequelize associations and models are no longer being acknowledged without any alterations made. A general error is displayed stating, 'Cannot Read Property 'field' of undefined'

I've been working on a project using React, Node, Sequelize, and Redux for a while now, and everything was running smoothly. However, the other day I decided to update some of my Node packages, as I usually do, but after running npm update --save/--sa ...

Unexpected behavior with promise resolution in Node.js

I'm currently developing a web project using NodeJS, Express, Mongoose, and MongoDB. The following code snippet is functioning correctly: var findRecord = function(id) { // locate record by id return User.findOne({ _id: id }).then(function ...

Tips for capturing async errors in Node.js Express beyond the request context?

In my express server setup, I have implemented a functionality where a POST request triggers a lengthy job and returns a unique job ID. The server continuously monitors the status of the job, allowing the client to check for updates over time. To achieve t ...

Can you please explain the meaning of this statement in JavaScript/Node.js with regards to the importance of the => operator and the async and await keywords being used here?

(1) This snippet of code is used to hash a password, but the syntax may be unclear. Why does it utilize async and await in this manner? And why doesn't the => symbol seem to define a function? const hashPassword = async password => await bcrypt.ha ...

Keep a vigilant eye on the peak utilization of memory within the Node.js process

I am in search of a way to effectively monitor the maximum memory usage in a Node.js process, regardless of whether there are memory leaks or not. The processes in question include both real applications and synthetic tests. My expectation is that it sho ...

Bypassing the "Your connection is not private" error in NodeJS + Express with fetch() using Javascript

Presently, I have a setup with a NodeJS + ExpressJS client-side server that communicates with the back-end server via API calls. However, every time I make a call, I need to manually navigate to the URL of the API back-end server and click on Advanced -> P ...

Encountering errors: Time-zone discrepancies arise when making API calls from AngularJS and querying results from Firebase using NodeJS

Whenever I try to query with a date range, the results returned are incorrect. I have implemented DateRangePicker jQuery for selecting both date and time ranges. After that, I make an API call and send my date/Moment JS object to my Node.js API where I q ...

What is the best way to integrate the nodemailer feature into the existing controller function?

I am currently working on developing a form that will first send data to MongoDB and then transfer that data via email using Nodemailer. Below are the two functions involved: Controller Function exports.createListing = (req, res) => { // Validatin ...

Tips for extracting JSON data from an API with identical names as values

I am working on a project to create a data search system using JSON. The JSON data is stored in a REST API, and the structure of the API is as follows: [ { "info": "cute but big animal", "type": "pig", ...

Exploring the Possibilities with NodeJS and Socket.IO

I've encountered an interesting issue with my use of NodeJS and Socket.io. The server receives data through ZeroMQ, which is working perfectly fine. However, when there are a large number of connected clients (over 100), it appears that there is a de ...

Mistakes While Running Cordova Commands (Maka-CLI Application on an Android Device)

Recently, I attempted to launch a Maka-CLI web application on my Android device using the command "maka run android-device". Unfortunately, I encountered an error that persists and displays the following message: => Errors executing Cordova commands: Whi ...

Storing image links in a MongoDB database without converting the images to base64 allows for easier management and faster retrieval of the images. Additionally, by implementing a way

Is there a way to store image links in MongoDB without converting images to base64 and easily add new pictures to the database upon deployment? I've tried using the multer package, but newly uploaded images are not displaying on deployment. Additional ...

"Encountering a Type Error in Express.js When Trying to Import Database Schema

Currently working on a small web app using the MEAN stack and going through the process of moving my schemas to a separate "models" directory. Everything runs smoothly when the schemas are within the same app.js file, but once I organize them into a modula ...

Deploying a single node.js app on two separate servers and running them simultaneously

Is it possible to set up my game to run on both the west coast and east coast servers, while still using the same domain? In my code structure, app.js runs on the server with the home route serving as the entry point for the game. This means that users si ...

Convert CSV files to JSON format through file upload

Is there a way to convert a CSV file into a JSON Array object by uploading the file? I have attempted to use multer for this task. module.exports = function(express, app, upload){ var router = express.Router(); var util = require('util' ...