I have a problem populating data in mongoose.
here’s my code for models definition:
const CardSchema = new Schema({
name:{type:String,required:true},
short_name:{type:String,required:true},
img:{type:String},
type:{type:String,required:true},
suit:{type:String,required:false},
meaning:{type:String,required:true}
})
const Card = model('Card',CardSchema)
module.exports = Card
and
const {Schema,model} = require('mongoose')
const User = require('./User')
const Card = require('./Card')
const AlignmentSchema = new Schema({
name:{type:String,required:true},
userId:{type:Schema.Types.ObjectId, ref:User, required:true},
cards:[{type:Schema.Types.ObjectId,ref:Card,required:true}]
})
const Alignment = model('Alignment',AlignmentSchema)
module.exports = Alignment
so I want to populate cards:
class AlignmentController{
async create(req,res){
const {name,cards,userId} = req.body
const alignment = await Alignment.create({userId,name,cards})
console.log(alignment.cards.length)
return res.json(alignment)
}
async getAll(req,res){
const alignments = await Alignment.find({})
return res.json(alignments)
}
async getOne(req,res){
const {id} = req.params
const alignment = await Alignment.findById(id)
console.log(alignment.cards.length)
return res.json(alignment)
}
}
but I get only one populated card instead of populated array of cards. what is wrong?