I'm trying to populate a mongoose query with an array of objectId field. In another field with single objectId ref is working fine.
That's my "User" model:
const User = new Schema({
nome: {
type: String,
required: true
},
email: {
type:String,
required: true
}
})
mongoose.model('users',User)
That's my "Pedido" model:
const Schema = mongoose.Schema
const Pedido = new Schema({
id: {
type: String,
required: true
},
cliente: {
type: Schema.Types.ObjectId,
ref: 'clientes',
required: true
},
fotografos: {
type: [Schema.Types.ObjectId],
ref: 'users'
}
})
mongoose.model('pedidos',Pedido)
my router:
router.get('/pedidos',async(req,res)=>{
var query = await Pedido.find().populate('fotografos').populate('cliente').lean().exec()
console.log(query)
res.render("admin/pedidos",{pedidos: query})
})
That's the result in the console.log:
[
{
_id: 5e8e3bd16c57021f682b8e81,
fotografos: [],
cliente: {
_id: 5e8ccceea8a28146d86f4cac,
nome: 'Neymar',
email: 'neymar@ney.com',
__v: 0
},
__v: 0
}
]
fotografos field (array) are returning empty. clientes field returns populated.
Can anybody help me with this?
You can use this code...
fotografos:[{
type: [Schema.Types.ObjectId],
ref: 'users'
}]
**Then do Populate**