【问题标题】:Mongoose populate by field not _idMongoose 按字段而不是 _id 填充
【发布时间】:2021-10-04 22:58:55
【问题描述】:

我有这两个架构

const User = new mongoose.Schema({
    username: {
       type: String,
       unique: true,
    }

})

const Product = new mongoose.Schema({
    
    user: {
       type: mongoose.Schema.Types.ObjectId,
       ref: "User"
    }
     
    //...Other product information 

})

当我查询产品时,我可以像这样填充产品用户

await database.Product.findOne({}).populate("user")

这将通过他的id 填充用户,但我想通过他的用户名填充用户,因为它永远不会重复并且它是独一无二的。我有一种方法可以通过_id以外的其他字段引用模型

【问题讨论】:

    标签: node.js mongodb mongoose mongoose-populate


    【解决方案1】:

    这样做:

    await database.Product.findOne({}).populate('user',{path: 'username'})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-30
      • 2020-07-20
      • 2012-01-22
      • 2015-09-19
      • 2015-03-25
      • 2017-05-21
      • 2019-10-19
      相关资源
      最近更新 更多