What is the best way to retrieve all records from a MongoDB collection?

I am currently delving into the realm of JavaScript and MongoDB while attempting to construct a basic blog engine. My goal is to retrieve all blog posts stored in MongoDB so that I can utilize this data to populate an EJS template. Although I successfully achieve the desired output using console.log, I encounter an issue when attempting to store the function result in a variable as it returns excessive data.

Here is the code snippet:

mongoose.connect('mongodb://localhost/blog', {useNewUrlParser: true});

    const Schema = mongoose.Schema;
    const BlogSchema = new Schema({
        title : String,
        image: String,
        body: String
    });

    const Model = mongoose.model;
    const BlogPost = new Model('posts', BlogSchema);

    BlogPost.find((err, posts) => {
        console.log(posts);
    });
    

This generates the desired results in the log:

[
      {
        _id: new ObjectId("62ef1ea68a82d65948539324"),
        title: 'Test Title',
        picture: 'n/a',
        body: 'this is the body of the test post'
      },
      {
        _id: new ObjectId("62ef202670ad070b78e928a3"),
        title: 'Test Title 2',
        picture: 'n/a',
        body: 'this is the body of the second test post'
      }
    ]
    

However, if I try the following code:

const mongoose = require('mongoose');
    mongoose.connect('mongodb://localhost/blog', {useNewUrlParser: true});

    const Schema = mongoose.Schema;
    const BlogSchema = new Schema({
        title : String,
        image: String,
        body: String
    });

    const Model = mongoose.model;
    const BlogPost = new Model('posts', BlogSchema);

    var AllPosts = BlogPost.find((err, posts) => {
        posts;
    });

    console.log(AllPosts);
    

I receive this overwhelming response:

Query {
      // Data
    }
    

What could be the error in my approach?

Appreciate your help!

Answer №1

I recommend using async/await calls instead. Currently, your AllPosts variable is assigned a Promise as its value. Simply switch it to:

var AllPosts = await BlogPost.find({});

console.log(AllPosts);

Answer №2

let posts = await BlogPost.getAll()

/*OR*/

let posts = {};
BlogPost.find({}).then(response=>
{
 posts = response;
})
.catch(error=>
   {
       console.error(error);
   })

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

AngularJS and adding to an array in the routing process

I'm currently working on creating a contact list with two different views. One view displays all the contacts and includes an option to add a new contact, which is represented by a button rather than a space to input information directly. The other vi ...

What sets Observables (Rx.js) apart from ES2015 generators?

From what I've gathered, there are various techniques used for solving asynchronous programming workflows: Callbacks (CSP) Promises Newer methods include: Rx.js Observables (or mostjs, bacon.js, xstream etc) ES6 generators Async/Await The trend ...

Unable to set DIV to 'inline-block' or none based on checkbox selection

Despite reviewing multiple examples, I am still struggling to make this DIV visible and hidden by clicking a checkbox. Can someone please review my JavaScript code? <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Conten ...

Trouble with scrolling on Kendo chart while using mobile device

I am facing an issue with multiple kendo charts on my website. These charts have panning and zooming enabled, but in the mobile view, they take up 100% of the width which causes touch events to not work properly for scrolling. I attempted to attach an even ...

Creating resizable rows of DIVs using jQuery

I'm currently developing a scheduling widget concept. The main idea is to create a row of DIVs for each day of the week. Every row consists of a set number of time periods represented by DIVs. My goal is to enable the resizing of each DIV by dragging ...

What caused the failure of this discord.js query to mongoose?

Why is the code not working when trying to submit data to MongoDB using a discord.js command? const subregis = "!reg ign: "; client.on("message", msg => { if (msg.content.includes(subregis)){ const user = new User({ ...

Retrieve the property of an object from within an array

I am dealing with an array structure like this: const arr = [{ name: 'One', id: 1 }, { name: 'Two', id: 2 } ]; My goal is to extract and return the name of the object if its id matches a certain value. After exp ...

Tips for transferring information between two components when a button is clicked in Angular 2

I am currently working on a code that displays a table on the main page with two buttons, "Edit" and "Delete", for each row. When the Edit button is clicked, a modal opens up. My question is, how can I pass the "employee id" of a specific employee to the ...

Receiving a 401 error when making an Axios post request

Having trouble with a 401 error when making a POST request to an API? Don't worry, I've got some suggestions that might help. I'm able to successfully make GET requests to the same API with a 200 status, so it could be a syntax issue in the ...

What are the counterparts of HasValue and .Value in TypeScript?

There is a method in my code: public cancelOperation(OperationId: string): Promise<void> { // some calls } I retrieve OperationId from another function: let operationId = GetOperationId() {} which returns a nullable OperationId, operat ...

Navigating Through Secondary Navigation with Ease

In my React project, I am developing a mega-menu styled dropdown navigation. As a functional component, I am utilizing the useState hook to manage the state and control the display of sub-navigation items. The functionality of the dropdown is operational, ...

What is the best way to prevent a fetch request from being initiated before the authentication token has been received

After successfully logging in, the data request fetch function needs to send the request with the saved token bearer. However, the data fetch is not waiting for the token and is receiving an Unauthorized access code. This is how my data request fetch func ...

The specified container does not exist in the DOM: MERN

I am currently working on a project where I aim to develop a Web Application featuring a stock dashboard. During my coding process, I encountered a minor issue that can be seen in this image. My goal is to have a login form displayed on the browser using ...

Using AJAX to submit a form and retrieve response data in Javascript

After successfully getting everything to post correctly, I encountered a problem with this script. It keeps loading the content into a new page. Could it be related to the way my php file returns it using "echo(json_encode($return_receipt));"? <s ...

How to reposition the Bootstrap navbar Logo from the left to the center

I am looking to change the ordering of Bootstrap 4 Navbar. Currently, the logo is on the left side, but I want it in the center with menus on both sides. Can someone help me with changing this order? Check out the current Navbar layout below: <nav c ...

MUI options - The specified type 'string' cannot be matched with type '"icon" | "iconOnly" | "text" | "outlined" | "contained" | undefined'

Is it possible to utilize custom variants in MUI v5? I am having trouble using a custom variant according to their documentation: https://mui.com/material-ui/customization/theme-components/#creating-new-component-variants declare module "@mui/material ...

How does the useEffect React hook perform its comparison process?

One of my favorite JavaScript expressions is: []==[] // false Let's now explore what the React documentation says about skipping side effects: React allows you to skip applying an effect if certain values have not changed between re-renders. To a ...

Can Angular's built-in internationalization features be used to translate bindings?

Challenge The task at hand involves integrating translations into an Angular 6 application to support static text in multiple languages. The objective is to have the ability to choose a language during the build process without requiring dynamic translati ...

Building interactive web forms with real-time validation using CodeIgniter

I'm looking for a way to use ajax (jquery library) to validate my forms. Specifically, I have a form that requires a minimum password length of 6 characters. Currently, I have implemented the validation rule as follows, $this->form_validation-> ...

What is the best way to set up TypeScript to utilize multiple node_modules directories in conjunction with the Webpack DLL plugin?

Utilizing Webpack's DllPlugin and DllReferencePlugin, I create a distinct "vendor" bundle that houses all of my main dependencies which remain relatively static. The project directory is structured as follows: project App (code and components) ...