John Kahn
John Kahn

Reputation: 308

Populate document if there is no value, using MongooseJS

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 protected]",
    "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?

Upvotes: 2

Views: 429

Answers (1)

Robert Moskal
Robert Moskal

Reputation: 22553

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.

Upvotes: 1

Related Questions