Search code examples
node.jsmongodbmongoosemongoose-populate

Mongoose populate by field not _id


I have these two schema

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 

})

and when I query product I can populate the product user like this

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

this will populate the user by his id but I want to populate the user by his username since it never gonna repeat and it's unique. I there is a way to reference a model by another field other than the _id


Solution

  • Do this:

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