I have problem with populating my OfferSchema.
When I'm trying to get booked offers of current user, I'm getting MissingSchemaError: Schema hasn't been registered for model "offer"
error from mongoose.
tenant field populate correctly.
I have tried many ways to fix this problem even from official docs, but no one pass for me. I will appreciate any help, thanks.
const BookSchema = new Schema({
tenant: {
type: Schema.Types.ObjectId,
ref: 'user'
},
...
offer: {
type: Schema.Types.ObjectId,
ref: 'offer'
}
});
const BookModel = mongoose.model('books', BookSchema);
module.exports = BookModel;
const OfferSchema = new Schema({
...
author: {
type: Schema.Types.ObjectId,
required: true,
ref: 'user'
}
});
const OfferModel = mongoose.model('offers', OfferSchema);
module.exports = OfferModel;
const landlord = req.userData.userId;
Book.find().populate('tenant', 'email').populate({
path: 'offer',
match: {
'author': {
$eq: landlord
}
}
}).then(books => {
res.status(200).json({books: books})
}).catch(err => {
console.log(err);
res.status(500).json({error: err.message})
});
I have solved my problem in some different way.
Now I'm search for booked offers of current user like this, hope it would be useful for someone in future.
exports.get_landlord_books = async (req, res) => {
let offers = await Offer.find( {author: req.userData.userId});
if (offers) {
Book.find({
'offer': { $in: offers}
}).populate('tenant', 'email').then(books => {
res.status(200).json({books: books})
}).catch(err => {
console.log(err);
res.status(500).json({error: err.message})
});
} else {
console.log('no booked offers for this user')
}
};