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!