Using two Mongoose collections on a single webpage with Express

There is an issue with my Express route that fetches data from two separate MongoDB collections. One collection displays the results correctly, but the other does not (I have defined schemas for both).

router.get('/demo/:cars_getroute', (req, res, next) => {
    Democar.findOne({ cars_getroute: req.params.cars_getroute })
        .then((democars) => {
            res.render('demo/fichecar-demo', { marque: democars.marque,
                modele: democars.modele,
                sous_modele: democars.sous_modele,
                sous_modele2: democars.sous_modele2,
                type: democars.type
            });
            Democarauction.findOne({ cars_getroute: req.params.cars_getroute })
                .then((democarauctions) => {
                    res.render('demo/fichecar-demo', { marqueauction: democarauctions.gm_url });
                });
        });

})

Any suggestions on how to display data from the second collection on the page?

EDIT: Here are my models:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

//Create Schema for Car
const CarSchema = new Schema({
    // Fields and Types here...
},
{
    collection: 'carfiche2019'
});

mongoose.model('cars', CarSchema);

DemoCarauction Schema:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

//Create Schema for Democarauction
const DemocarauctionSchema = new Schema({
    // Fields and Types here...
},
    {
        collection: 'democarficheauction'
    });

mongoose.model('democarauctions', DemocarauctionSchema);

Answer №1

Rendering twice is not recommended. It is advisable to utilize Promise.all

router.get('/demo/:cars_getroute', (req, res, next) => {
    Promise.all([Democar.findOne({cars_getroute: req.params.cars_getroute}), Democarauction.findOne({ cars_getroute: req.params.cars_getroute })])
    .then(result => {
        const [democars, democarauctions] = result;
        res.render('demo/fichecar-demo', { marque: democars.marque,
            modele: democars.modele,
            sous_modele: democars.sous_modele,
            sous_modele2: democars.sous_modele2,
            type: democars.type,
            marqueauction: democarauctions.gm_url
        });
    })
    .catch(err => {
        // handle error. 
        console.log(err);
    })

});

Remember to include a catch block for error handling.

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

Unable to generate bundle.js file

I am currently working on building a basic webpack project using Visual Studio Code. The project consists of two main folders: 1. dist 2. src Within the src folder, I have an app.js file that I would like to bundle using webpack. To achieve this, I attem ...

Is there a way to utilize javascript std input/output in repl.it effectively?

I created a straightforward program that calculates the factorial of a specified number, and I am interested in running it on repl.it. During its execution, I would like to interact with standard input and output through the command line. Is there a way ...

Creating a custom Koa.js server in a Next.js application

I'm facing an issue with my custom koa.js server. Whenever I try to make a request to the API, like /api/login I always end up getting a 404 not found error. I have searched for a solution but haven't been able to find one. Here is a snippet f ...

Utilize the HTTP.get function to serve files in the img src attribute

I am facing an issue where my file can only be accessed if I include an x-authentication token in the header of the "GET" http request. Unfortunately, using a cookie is not an option in this case. This means I cannot simply call for the file by its URL in ...

Ensuring secure passwords through express-validation for password equality validation

Looking for guidance on validating form inputs with express-validation. Overall, everything is functioning properly except for checking if the password fields match. // form validation req.checkBody('name', 'Name is required').notEmpty ...

Encountering a issue with calling a Mongoose static method from a post hook in Mongoose

I'm attempting to invoke a static method in Mongoose from a post hook method for 'deleteOne'. However, I am encountering the following error message: this.constructor.calculateAverageRating is not a function reviewSchema.statics.calculateAve ...

Accessing a parent class constructor object in NodeJS from the Child Class

I'm currently working on creating a Controller Class that will handle the initialization of all my routes using ExpressJS. Below is a simple example of what I have so far: class Test extends Controller { constructor(App) { const Routes = [ ...

Automaton ScheduleTask Feature

I'm struggling to understand how to make this work. My goal is to set up Hubot to automatically call a function at regular intervals in a specific HipChat channel. Currently, I have it working by requiring the user to type "Hubot totalviewers" in the ...

Struggling with resolving unresolved dependencies

I have encountered issues when updating npm packages during an upgrade process. It seems that angular/core has unmet dependencies, as indicated below. I am curious to know the meaning of symbols such as '+', '-', ' ` '? T ...

Using a toolbar to insert a hyperlink for hypertext communication

My journey with Javascript and React began this week, so I'm still getting the hang of things, especially in the front end domain. In my project, there's a link button within a toolbar. The idea is to click on it, have a text box pop up where yo ...

Testing asynchronous callback timeouts using sinon, jest, and supertest to create a simulated error 500 response on an Express API

I am currently running tests on an API that consistently returns HTTP 500 errors. I have attempted to use sinon.stub to test a failing server and receive a 500 error, but I keep encountering timeout async callbacks. When using my app, however, I sometimes ...

Enhance a model in the Mean Stack with Node.js and Mongoose integration

Encountering an issue with updating a model in my API. Currently utilizing a Mean Stack with "express": "^4.14.0" and "mongoose": "^4.7.2", along with mongodb 3.2.11 Upon attempting to PUT the changes to the API, receiving an OK status, however, the resou ...

Updating multiple documents using Mongoose with a specified condition

I am currently attempting to update all documents within my MongoDB database using Mongoose. While I know this question has been asked before, I have not found the answer that suits my specific needs. I am utilizing version 4.2 I am endeavoring to use upd ...

Guide for launching Electron on a local host server during development and for production builds

I have a project using Next.js + Electron + Typescript. I used the npx create-next-app --example with-electron-typescript command to generate the initial code. When I run npm run dev (which actually runs npm run build-electron && electron . ), the ...

Addressing the issue of prolonged Electron initialization

Scenario After spending considerable time experimenting with Electron, I have noticed a consistent delay of over 2.5 seconds when rendering a simple html file on the screen. The timeline of events unfolds like this: 60 ms: app ready event is triggered; a ...

Executing a raw query within an express.js route using sequelize

I'm currently a beginner in using sequelize. I have a node.js project set up with sequelize cli and am attempting to execute a raw query within a "put" express route of my application. However, I keep encountering an error: Sequelize.query is not a ...

Populate MongoDB collection with pre-existing product data

I'm working on a project using Meteor and React. I want to populate my Product collection with data so that when users run the app, they can see products on the client side. The fields would include: ProductName: String, ProductPrice: Number, ProductC ...

When making a POST request, req.session.userId is returning as undefined

After using req.session.userId = user._id; in the post request on route /signin, I encountered an issue where console.log(req.session.userId) returns the user id as expected. However, when I try to access req.session.userId in a post request on route /note ...

What is the best way to add a base path to every route managed by Next.js?

Currently, I am in the process of revamping an existing expressjs application that utilizes jade for the user interface to a nextjs application. The same app serves as the API server for external applications. All web app routes are currently located under ...

Main folder for Node.js module

We have a node module set up with Babel to transpile our code and output it to a 'lib' folder. In the package.json file, the main points to 'lib/index.js', allowing users to simply use require('my-module'). The issue arises w ...