Monday 30 March 2020

Mongoose populate() not working as desired

I have a PaymentCard and a User schema, and want to define an existing user's ID when creating a new PaymentCard record to link that specific card to a specific customer. It does create the PaymentCard document with the customer's mongoID, however querying with .populate() does not return any cards on any of the users, and return empty arrays on all users.My Customer Schema:const Customer = new Schema({ name: { type: String, required: true }, surname: { type: String, required: true }, alias: String, customerStatus: { type: String, enum: ['Regular', 'Valued'], }, discount: { type: String, enum: ['Fixed', 'Flexible'] }, email: String, phoneNo: String, cards: [{ type: Schema.Types.ObjectId, ref: 'paymentcards' }] }) module.exports = mongoose.model('Customer', Customer ) My PaymentCard Schema:const PaymentCard = new Schema({ owner: { type: Schema.Types.ObjectID, ref: 'customers' }, nameOnCard: { type: String, required: true }, cardNumber: { type: String, required: true, unique: true, minlength: 15, maxlength: 16 }, cardIssuer: String, cvc: Number, exp: { type: Number, } }) module.exports = mongoose.model('PaymentCard', PaymentCard) The two functions I use to register a new card and get a list of all customers:router.post('/addPayment', (req, res, next) => { jwt.verify(req.query.secret_token, process.env.JWT_SECRET, (err, decoded) => { if (decoded.user.role == 'Advisor') { PaymentCard.create({ owner: req.body.owner, nameOnCard: req.body.nameOnCard, cardNumber: req.body.cardNumber, cardIssuer: req.body.cardIssuer, cvc: req.body.cvc, exp: req.body.exp }) res.send('Registered successfully'); } else { res.status(401).json({ message: 'Unauthorised' }) } }) }) router.get('/getAll', (req, res, next) => { jwt.verify(req.query.secret_token, process.env.JWT_SECRET, (err, decoded) => { if (decoded.user.role == 'Manager' || 'Advisor') { Customer.find({}, function (err, customers) { res.send(customers); }).populate('cards').exec((err, cards) => { console.log("Populated User " + card); }) } else { res.status(401).json({ message: 'Unauthorised' }) } }) }); Can you see where my problem is?

Submitted March 30, 2020 at 06:17PM by Fizaraz

No comments:

Post a Comment