Home > other >  How do I return all documents in mongodb collection?
How do I return all documents in mongodb collection?

Time:08-07

I'm new to javascript and mongodb, and I'm trying to build a simple blog engine. I'm trying to return all of the blog posts within mongodb so that I can use that data to fill in a ejs template. I get the output I want with console.log, but when I try saving the function result to a variable, I get much more data than I need.

Here's the code:

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 produces what I want 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 this:

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 get this:

Query {
  _mongooseOptions: {},
  _transforms: [],
  _hooks: Kareem { _pres: Map(0) {}, _posts: Map(0) {} },
  _executionStack: null,
  mongooseCollection: Collection {
    collection: null,
    Promise: [Function: Promise],
    modelName: 'posts',
    _closed: false,
    opts: {
      autoIndex: true,
      autoCreate: true,
      schemaUserProvidedOptions: {},
      capped: false,
      Promise: [Function: Promise],
      '$wasForceClosed': undefined
    },
    name: 'posts',
    collectionName: 'posts',
    conn: NativeConnection {
      base: [Mongoose],
      collections: [Object],
      models: [Object],
      config: {},
      replica: false,
      options: null,
      otherDbs: [],
      relatedDbs: {},
      states: [Object: null prototype],
      _readyState: 2,
      _closeCalled: false,
      _hasOpened: false,
      plugins: [],
      id: 0,
      _queue: [],
      _listening: false,
      _connectionString: 'mongodb://localhost/blog',
      _connectionOptions: [Object],
      client: [MongoClient],
      '$initialConnection': [Promise]
    },
    queue: [],
    buffer: true,
    emitter: EventEmitter {
      _events: [Object: null prototype] {},
      _eventsCount: 0,
      _maxListeners: undefined,
      [Symbol(kCapture)]: false
    }
  },
  model: Model { posts },
  schema: Schema {
    obj: {
      title: [Function: String],
      image: [Function: String],
      body: [Function: String]
    },
    paths: {
      title: [SchemaString],
      image: [SchemaString],
      body: [SchemaString],
      _id: [ObjectId],
      __v: [SchemaNumber]
    },
    aliases: {},
    subpaths: {},
    virtuals: { id: [VirtualType] },
    singleNestedPaths: {},
    nested: {},
    inherits: {},
    callQueue: [],
    _indexes: [],
    methods: {},
    methodOptions: {},
    statics: {},
    tree: {
      title: [Function: String],
      image: [Function: String],
      body: [Function: String],
      _id: [Object],
      __v: [Function: Number],
      id: [VirtualType]
    },
    query: {},
    childSchemas: [],
    plugins: [ [Object], [Object], [Object], [Object], [Object] ],
    '$id': 1,
    mapPaths: [],
    s: { hooks: [Kareem] },
    _userProvidedOptions: {},
    options: {
      typeKey: 'type',
      id: true,
      _id: true,
      validateBeforeSave: true,
      read: null,
      shardKey: null,
      discriminatorKey: '__t',
      autoIndex: null,
      minimize: true,
      optimisticConcurrency: false,
      versionKey: '__v',
      capped: false,
      bufferCommands: true,
      strictQuery: true,
      strict: true,
      pluralization: true
    },
    '$globalPluginsApplied': true
  },
  op: 'find',
  options: {},
  _conditions: {},
  _fields: undefined,
  _update: undefined,
  _path: undefined,
  _distinct: undefined,
  _collection: NodeCollection {
    collection: Collection {
      collection: null,
      Promise: [Function: Promise],
      modelName: 'posts',
      _closed: false,
      opts: [Object],
      name: 'posts',
      collectionName: 'posts',
      conn: [NativeConnection],
      queue: [],
      buffer: true,
      emitter: [EventEmitter]
    },
    collectionName: 'posts'
  },
  _traceFunction: undefined,
  '$useProjection': true
}

What am I doing wrong?

Thank you!

CodePudding user response:

You should rather go with async/await calls. Right now your AllPosts variable has Promise as value. Just change it into:

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

console.log(AllPosts);

CodePudding user response:

var AllPosts = await BlogPost.find({})

/*OR*/

var AllPosts={};
BlogPost.find({}).then(data=>
{
 AllPosts=data;
})
.catch(err=>
   {
       console.log(err);
   })
  • Related