使用 mongoose 在 mongodb 中具有多个引用的消息模式

Message schema that has multiple refs in mongodb using mongoose

我被卡在这里了,因为我不确定如何为一个对象设置多个引用以指定它的 objectid。

例如:(如何指定发件人是Seller,也可以是User,还有,如果有这种情况,最好的做法是什么)

const messageSchema = mongoose.Schema({
  message: {
    text: { type: String, required: true },
    type: String, //type can be or 'message', 'image',
  },
  members: {
    seller: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Seller",
      required: true,
    },
    client: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User",
      required: true,
    },
  },
  sender: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User",
    required: true,
  },
  readOn: { type: Date },
  read: Boolean, //}, {
  timestamps: true,
});

我想说:

sender: {
    type: mongoose.Schema.Types.ObjectId,
    ref: ["User", "Seller"],
    required: true,
  },

这可能吗?非常感谢。

您可以使用 refPath 进行动态引用。

const messageSchema = mongoose.Schema({
  
 sender_type: String  // user or seller

 sender: {
    type: Schema.Types.ObjectId,
    refPath: 'sender_type'
  }
})

你可以使用虚拟

const messageSchema = new mongoose.Schema({
...
 sender: {
    type: mongoose.Schema.Types.ObjectId,
    required: true
  },
...
},
{
    toJSON: { virtuals: true }
});

然后像这样定义虚拟模式:

order_schema.virtual('User', {
    ref: 'User', // Your User model name
    localField: 'sender', 
    foreignField: '_id', 
    justOne: true
});

order_schema.virtual('Seller', {
    ref: 'Seller',
    localField: 'sender',
    foreignField: '_id',
    justOne: true
});

然后在数据库操作中定义两个populates:

Model.find(search_filter)
      .populate('User')
      .populate('Seller')