Mongoose 按字段填充而不是 _id

问题描述

我有这两个架构

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

以外的其他字段引用模型

解决方法

这样做:

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