平等搜索人口稠密的土地

问题描述 投票:0回答:1

我在填充OfferSchema时遇到问题。

当我试图获得当前用户的预订优惠时,我从mongoose得到MissingSchemaError: Schema hasn't been registered for model "offer"错误。

租户字段正确填充。

我已经尝试过很多方法来解决这个问题,即使是官方文档,但没有人通过我。我将不胜感激,谢谢。

我的图书模式

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})
});
node.js mongoose mongoose-schema mongoose-populate
1个回答
0
投票

我以某种不同的方式解决了我的问题。

现在我正在搜索这样的当前用户的预订优惠,希望它对将来有用。

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')
    }
};
© www.soinside.com 2019 - 2024. All rights reserved.