Home > Back-end >  Can not read data from local MongoDB using expressjs mongoose library
Can not read data from local MongoDB using expressjs mongoose library

Time:01-11

I am learning Mongoose and MongoDB and try to read data from a local hosted MongoDB, I typed similar example from Mongoose documentation. But it doesn't work. I create a simple MongoDB collection named blogs inside a database called personal_website for test purposes. And there is only one document in this collection

personal_website> db.blogs.find()
[ { _id: ObjectId("63bbcb27ae437ded486fecf4"), title: 'test' } ]

There is my code which doesn't work

user@user-machine: ~$ cat server.js

const mongoose = require("mongoose");
mongoose.set("strictQuery", true);
mongoose.connect("mongodb://localhost/personal_website", () => {
    console.log("connected to databse personal_website");
});

let blogSchema = new mongoose.Schema({
  title: String,
});

let Blog = mongoose.model("blog", blogSchema);

let blogCount = Blog.find({}).count();
console.log(blogCount);

I run node server.js but I got this output:

Query {
  _mongooseOptions: {},
  _transforms: [],
  _hooks: Kareem { _pres: Map(0) {}, _posts: Map(0) {} },
  _executionStack: null,
.........
connected to databse personal_website

I expect get the similar result as i run db.blogs.find().count() command in MongoDB shell. How could I fix that? Should I query database after the connection established? I saw a lot of tutorials connect to their MongoDB at the very beginning just like me and also the documentation says "Mongoose lets you start using your models immediately, without waiting for mongoose to establish a connection to MongoDB". So can you guys help me figure out what cause this problem and how to fix it? I really appreciate that, I stuck there like four hours.

CodePudding user response:

  1. use port number and 127.0.0.1 in your connection string: "mongodb://127.0.0.1:27017/personal_website" instead of "mongodb://localhost/personal_website" (27017 is default port)

  2. try to wrap your query with async function and use await:

async function count() {
  let blogCount = await Blog.find({}).count();
  console.log(blogCount);
}

count();
  • Related