我们什么时候应该在mongoose相关文档中使用ref?

时间:2022-01-19 20:47:47

I have a "User" and a "Notification" Collection in my Mongo database, should I relate them using id like so :

我的Mongo数据库中有一个“User”和一个“Notification”集合,我应该使用id来关联它们:

const NotificationSchema = new mongoose.Schema({
   type: {
      type: String,
      required: true
   },
   userId: {
     type: Schema.Types.ObjectId,
     required: true
   }
});

or using ref :

或使用ref:

userId: {
  type: Schema.Types.ObjectId,
  ref: 'User'
}

1 个解决方案

#1


0  

The required attribute is intended to specify that a field must be set.
To make a reference to another collection, you need to use the ref attribute:

required属性用于指定必须设置字段。要引用另一个集合,您需要使用ref属性:

userId: {
  type: Schema.ObjectId,
  ref: 'User',
  required: true
}

This will let you populate the User when you perform a query.

这将允许您在执行查询时填充用户。

#1


0  

The required attribute is intended to specify that a field must be set.
To make a reference to another collection, you need to use the ref attribute:

required属性用于指定必须设置字段。要引用另一个集合,您需要使用ref属性:

userId: {
  type: Schema.ObjectId,
  ref: 'User',
  required: true
}

This will let you populate the User when you perform a query.

这将允许您在执行查询时填充用户。