weichao.x
weichao.x

Reputation: 315

Is property `ref` necessary when schema field type is `ObjectId` in Mongoose?

I have a sample mongoose schema like below:

new Schema(
  {
    title: {
      type: String,
    },
    digest: {
      type: String,
    },
    owner: {
      type: ObjectId,
      ref: 'User'
    }
  }
)

I wonder to know that is property ref necessary when the field type is ObjectId like owner field.

Upvotes: 1

Views: 157

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230286

No, not necessary, but if you have it, you'll be able to easily load the referenced entities. http://mongoosejs.com/docs/populate.html

Kitten.findOne().populate('owner').exec(function (err, kitten) {
  console.log(kitten.owner.name) // Max
})

Without ref, it'll just be an ordinary field that contains ObjectId.

Upvotes: 2

Related Questions