【问题标题】:mongoose populate field without ref option没有参考选项的猫鼬填充字段
【发布时间】:2013-01-15 16:22:23
【问题描述】:

我有 3 个架构:

var User1Schema = new Schema({
    name: {type:String , trim: true, required: true },
    status: {type:Number, required: true, default:1}
},{collection:"user_1"});

,

var User2Schema = new Schema({
    name: {type:String , trim: true, required: true },
    email: {type: String, required: true, index: {unique: true} },
    status: {type:Number, required: true, default:1}
},{collection:"user_2"});

和

var ConversationSchema = new Schema( {

    participants: [{user:{type: ObjectId, required: true}],
    creator: {type: ObjectId, required: true},

    status: { type:Number, required: true, default:1 }

}, { collection:"conversation" } );

在 ConversationSchema 中,我有 creator 字段,现在有 ref 选项,因为它可以是 User1Schema 或 User2Schema 的类型。

如何使用 mongoose 填充创建者字段

【问题讨论】:

标签: node.js mongodb mongoose


【解决方案1】:

截至 2019 年 3 月 27 日,这样做的方法是:

1) 将要填充的字段设置为 ObjectId 而不提供参考。

var eventSchema = new Schema({
  name: String,
  // The id of the corresponding conversation
  // Notice there's no ref here!
  conversation: ObjectId
});

2) 在使查询与查询一起传递模式的模型时:

Event.
  find().
  populate({ path: 'conversation', model: Conversation }).
  exec(function(error, docs) { /* ... */ });

参考号:https://mongoosejs.com/docs/populate.html#cross-db-populate

【讨论】:

    【解决方案2】:
    Conversation.find().populate('creator', null, 'User2').exec(callback)
    

    docs 不清楚。很快就会更新。

    此外,v3.6 中的语法会更简单。

    【讨论】:

    • 这允许多引用字段,我想?例如,文档的 _author 可能是 User ObjectId 或它可能是 Organization ObjectId?
    • 是的,如果您知道需要哪个模型,您可以在查询时指定。
    • 这是否也适用于路径引用 ObjectId 的混合类型字段?
    • @KevinWang 看来!。只需确保 populate 调用的第三个参数是一个与您尝试填充的 mongoose 模型同名的字符串。
    • 如果我想在多个模型中填充创建者,例如 'User1' 和 'User2' 怎么办?我看到只填充了最后一个指定的模型,并且所有以前的模型都返回 null。
    猜你喜欢
    • 2014-11-01
    • 2017-09-13
    • 2015-01-13
    • 1970-01-01
    • 2021-05-06
    • 2020-07-25
    • 1970-01-01
    • 2020-11-19
    • 2014-01-08
    相关资源
    最近更新 更多