首页 > 解决方案 > 在 mongoose 的查询中引用另一个模型的字段

问题描述

我有以下两个方案

const postSchema = new Schema({
service: {
    type: Schema.Types.ObjectId,
    ref: 'Service',
    required: true
}
});

const serviceSchema = new Schema({
    title: {
        type: String,
        required: [true, 'required'],
        unique: true
    }
});

我需要找到与搜索词匹配但引用 Service 模型的标题字段的 Post 模型的文档。我正在使用以下查询

Post.find().populate({path:'service', match:{title:{$regex: term, $options:"i"}}}).exec();

是的,它执行查询,但与它不匹配的文档将它们返回为空。我应该如何进行查询?

我正在使用猫鼬 5.13.2

标签: node.jstypescriptmongoose-schemamongoose-populate

解决方案


推荐阅读