MongoDB使用findOne()按ID查询内嵌子文档失败返回404问题求助
问题根因
你存入数据时,内嵌的customer、movie子文档的主键字段名是id,但查询语句中使用的字段名是customer._id和movie._id,字段名不匹配导致永远无法命中已存储的rental记录,所以接口固定返回404。
修复方案
可任选以下一种方案适配:
方案1:修改查询逻辑适配现有存储结构
直接把查询字段名和存入的字段名对齐即可:
// 把customer._id改为customer.id,movie._id改为movie.id 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');
方案2:修改数据存储逻辑适配查询规则
如果你设计时本来就打算用_id作为内嵌子文档的主键,需要同步修改存入数据的字段名和对应Schema定义:
beforeEach(async () => { customerId = mongoose.Types.ObjectId(); movieId = mongoose.Types.ObjectId(); rental = new RentalCollectionClass({ customer : { _id : customerId, // 把id改为_id name : 'nandhini', phone : 12345 }, movie : { _id : movieId, // 把id改为_id title : 'movieTitle', } }); await rental.save(); });
注意:选该方案需要同时修改RentalCollectionClass的Schema定义,确保内嵌customer、movie子文档的主键字段为_id,否则存储时还是会自动生成id字段,导致查询不生效。
内容的提问来源于stack exchange,提问作者nandhini
相关产品推荐
相关产品推荐

