Chris
Chris

Reputation: 1584

How do I set a different type of property in mongoose schema from the defined type?

I have a Mongoose schema set up for a user profile on a forum. What I'd like to do is set up the user's forum title to be an ObjectID and reference the Title schema. I already have this part set up. However by default I'd like for this field to be a string called "Noob" until a title is set from the user's profile which then would change this value to an ObjectID referencing the Title from the database.

title: {
  type: mongoose.Schema.Types.ObjectId,
  ref: 'Title',
  default: 'Noob'
},

This is what I have and is basically what I'm wanting to achieve, however this throws an error because the default I set is a string and not an ObjectID. I'm not sure how to achieve this or what alternatives I may have.

Upvotes: 0

Views: 381

Answers (2)

brandonscript
brandonscript

Reputation: 72825

Since you've pointed out that you want to maintain the strong type ObjectId for performance reasons, you'll have to use that same type as the default. You could use an id of all 0s for example:

title: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "Title",
    default: 00000000-0000-0000-0000-000000000000
}

You can then check for this and display "Noob" in its place later?

Upvotes: 1

Josh Beam
Josh Beam

Reputation: 19772

You can just make it a string:

title: {
  type: String,
  ref: 'Title',
  default: 'Noob'
},

You can still set it as an ObjectID-looking string later.

You can't have it both ways: if you want a field to be an ObjectID type, then it needs to hold ObjectIDs. If you want to be able to hold strings in it, then it needs to be of type String.

If title is a reference to an ObjectID in another collection, Mongoose will still cast an ObjectID-ish string to an ObjectID when it performs the lookup:

Title.find({ _id: doc.title }) will still lookup an ObjectID if the doc.title is a string.

Upvotes: 0

Related Questions