Mongoose query return null

Viewed 19669

I can't seem to get a response from mongodb. I am using node.js and mongodb with the help of mongoose.

In my node.js app I have

mongoose.connect('mongodb://localhost:27017/myDB');

var Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId;

var BlogPost = new Schema({
    author  : ObjectId,
    title   : String,
    slug    : { type: String, lowercase: true, trim: true },
    content : String,
    summary : String,
    date    : Date
})

var BlogModel = mongoose.model('BlogPost', BlogPost);

BlogModel.find({}, function(docs){
   console.log(docs);
});

If I type show dbs in the mongo shell I get

admin   (empty)
myDB       0.203125GB
local   (empty)
test    (empty)

db.blogmodel.find() returns :

{ "_id" : ObjectId("50108d3df57b0e3375a20479"), "title" : "FirstPost" }

and yes I do have mongod running.

Fixed Solution

var BlogModel = mongoose.model('blogmodel', BlogPost, 'blogmodel');

It works because its (model name, schema name, collection name)

4 Answers

For anyone still experiencing this issue even after checking the accepted answer – make sure your database connection url contains the database name, e.g. for database name myDB...

mongoose.connect(`mongodb://localhost:27017/myDB`)

I'd forgotten it and my mongoose searches were all returning null or empty arrays.

Related