[英]Nest.js MongoDb always return results
因此,即使没有与搜索查询匹配的结果,find 方法也会始终返回结果。 可能是什么原因?
架构:
export const ReviewScehma = new mongoose.Schema({
reviewId: { type: String, default: '' },
authorName: { type: String, default: '' },
packageIdentifier: { type: String, default: '' },
userComment: {
text: { type: String, default: '' },
starRating: { type: Number, default: 0 }
});
搜索:
async reviews(packageIdentifier: string) {
const searchTerms = (packageIdentifier) ? { packageIdentifier: packageIdentifier } : {};
const reviews = await this.reviewModel.find( searchTerms );
if (!reviews) {
throw new NotFoundException('There are no reviews to fetch');
}
return reviews;
}
我的收藏中目前有 100 个对象,其中只有一个带有packageIdentifier
和 value。 当他找不到任何东西时,我怎样才能让他返回一个空数组? 或者,当然,当他们这样做时,还有一系列结果。
目前,它总是返回整个集合。
如果您需要根据匹配值查找数据,那么您需要使用条件更改查找查询,如果您传递{}
,它将返回所有文档。
async reviews(packageIdentifier: string) {
const reviews = await this.reviewModel.find({$and: [{ packageIdentifier: {$exists: true}}, { packageIdentifier }]});
if (!reviews) {
throw new NotFoundException('There are no reviews to fetch');
}
return reviews;
}
如果有匹配的文档,它将返回数据,否则它将返回[]
。
空查询过滤器会导致 Mongoose/MongoDB 返回 model 中的所有文档,从而导致此问题。 为了实现所需的功能,您应该将strict
和strictQuery
选项传递给您的架构。
export const ReviewScehma = new mongoose.Schema({
reviewId: { type: String, default: '' },
authorName: { type: String, default: '' },
packageIdentifier: { type: String, default: '' },
userComment: {
text: { type: String, default: '' },
starRating: { type: Number, default: 0 }
}, { strict: true, strictQuery: false });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.