问题描述
我有这两个架构
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'})