2

Let's say I have a User model like this

var userSchema = new Schema({
    username : String,
    email    : String,
    project  : {type : String, ref : "Project"}
});

and a User document like this.

{
    "_id"      : ObjectId("56df56c58a4d47c83bf41603"),
    "username" : "user1",
    "email"    : "email@example.com",
    "project"  : "",
    "__v"      : 1
}

If I do the following, the page never loads.

User.findById("56df56c58a4d47c83bf41603").populate("project").exec()
.then(function(userObj) {
    res.render('user', {
        user : userObj
    });
});

It works fine if there is an actual ObjectID in there, but not when it is blank.

Is there a way that I can default to null if there is no ObjectID in the value?

John Kahn
  • 308
  • 1
  • 11
  • Are you saying the promise never gets resolved if the document doesn't exist? I find that hard to believe. – Robert Moskal Jun 05 '16 at 22:52
  • Unless there is an error. Maybe you should be trapping the exception condition to see what's up. – Robert Moskal Jun 06 '16 at 00:42
  • I don't know what's happening. All I know is that when there is an empty string instead of an ObjectId in there, it will never load the page. It will eventually time out. I'll see if I can find an error and I'll add it above. – John Kahn Jun 06 '16 at 00:42
  • Got it. Whenever you are storing it as a string instead of an Schema.Types.ObjectId it tries to cast it. It does not know how to cast an empty string. If the string is left as null it works fine. I changed it to ObjectId and fixed the existing documents and now it all works. – John Kahn Jun 06 '16 at 01:53

1 Answers1

1

So the answer to the question is here:

Mongoose: CastError: Cast to ObjectId failed for value "[object Object]" at path "_id"

An empty string will throw a cast error. Your weren't trapping the exception from the promise based call and so your route was timing out.

The lesson is to trap the exception. Just like you would if you were using callbacks.

Community
  • 1
  • 1
Robert Moskal
  • 21,737
  • 8
  • 62
  • 86