首页 > 解决方案 > 无法使用 findOne() 通过 id 在 mongodb 中找到子文档

问题描述

检查状态 200 和状态 400 的测试用例失败。在这两种情况下,我都收到了 404 状态,这意味着租借在 db 中不存在。

const rental_exists = await RentalCollectionClass.findOne({
                                                    "customer._id" : req.body.customerId,
                                                    "movie._id" : req.body.movieId });
        if(!rental_exists) 
            return res.status(404).send('Rental with given customer/movie not in db'); 
        if(rental_exists.dateReturned)         
            return res.status(400).send('Rental with given customer/movie already processed');   
        return res.status(200).send('Valid rental posted');  

但是我在测试用例的 beforeEach() 函数中创建了租用,如下所示。

beforeEach(async () => {
        customerId = mongoose.Types.ObjectId();
        movieId = mongoose.Types.ObjectId();
        rental = new RentalCollectionClass({
            customer : {
                id : customerId,
                name : 'nandhini',
                phone : 12345
            },
            movie : {
                id : movieId,
                title : 'movieTitle',
            }
        });
        await rental.save();
    });

另请注意,客户和电影是租赁的子文件。请帮我解决这个问题!!

标签: node.jsmongodbjestjshttp-status-code-404subdocument

解决方案


推荐阅读