Search code examples
node.jsmongodbshellmongoosemongo-shell

mongoose query doesnt work in node.js but works in mongo shell


I am trying to get a list of todos based on the 'userId' stored against the todo. Using the following code returns no rows.

DB.TodoTable.find({ "userId" : ObjectId("54c12f5f3620c07019e6b144") }, function(err, todos) {
    if (err) return console.error(err);

    console.dir(todos);
})

the mongoose debug gives:

Mongoose: todos.find({ userId: undefined }) { fields: undefined }
[]

But whenn i try the same in mongo shell, it works. As follows:

> db.todos.find()
{ "_id" : ObjectId("54c12f643620c07019e6b145"), "created_at" : ISODate("2015-01-22T17:12:04.932Z"), "userId" : ObjectId(
"54c12f5f3620c07019e6b144"), "text" : "data", "__v" : 0 }

My database schema is as follows:

var TodoTable = mongoose.model('todos', {
    text : {type : String, default: ''},
    created_at : Date,
    userId : {type:ObjectId, ref:'users'}
});

var UserTable = mongoose.model('users', {
    username: String,
    password: String,
    email: String,
    gender: String,
    address: String
});

Solution

  • Confusingly, mongoose.Schema.ObjectId is not the ObjectID constructor function, it's only meant to be used in defining schemas.

    But you don't need to create an ObjectID from that string anyway because Mongoose will do that for you based on the schema definition, so you can simply use:

    DB.TodoTable.find({ "userId": "54c12f5f3620c07019e6b144" }, function(err, todos) {...})
    

    Or if you are in a situation where you need to be explicit, you can access the ObjectID constructor as:

    DB.TodoTable.find({ "userId": mongoose.mongo.ObjectID("54c12f5f3620c07019e6b144") }, 
        function(err, todos) {...})