Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose query return null

Tags:

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)

like image 887
lostAstronaut Avatar asked Jul 26 '12 02:07

lostAstronaut


People also ask

How to query null values in MongoDB?

MongoDB fetch documents containing 'null' If we want to fetch documents from the collection "testtable" which contains the value of "interest" is null, the following mongodb command can be used : >db. testtable. find( { "interest" : null } ).

Why is findById return null?

findById returns the document where the _id field matches the specified id . If the document is not found, the function returns null .

What does findById return in Nodejs?

findById() function is used to find one document by its _id . The findById() function takes in a single parameter, the document id. It returns a promise that resolves to the Mongoose document if MongoDB found a document with the given id , or null if no document was found.

Does Mongoose save overwrite?

Mongoose save with an existing document will not override the same object reference. Bookmark this question.


2 Answers

Mongoose pluralizes model names so it's running find on the "blogposts" collection instead of "blogpost". That said, your query in the mongo shell is on the "blogmodel" collection. In that case:

var BlogModel = mongoose.Model("BlogModel", ..) 

or pass the collection name as the third param:

var BlogModel = mongoose.model("BlogPost", schema, "blogmodel") 
like image 175
aaronheckmann Avatar answered Oct 10 '22 17:10

aaronheckmann


The first parameter to your BlogModel.find callback is err, the second parameter is docs. So your code should be:

BlogModel.find({}, function(err, docs){    console.log(docs); }); 
like image 38
JohnnyHK Avatar answered Oct 10 '22 17:10

JohnnyHK