【发布时间】:2019-11-14 23:13:58
【问题描述】:
我正在尝试根据用户的多项选择进行动态查询。
在我的应用程序中,我的发布模式嵌入了 Pet 模式,如下所示:
var status = ["public", "private", "deleted"];
var publication_schema = new Schema({
pet:{
type: Schema.Types.ObjectId,
ref: "Pet"
},
status: {
type: String,
enum: status,
default: status[0]
}
});
module.exports = mongoose.model('Publication', publication_schema);
var pet_schema = new Schema({
type: {
type: String,
require: true
},
createdDate: {
type: Date,
default: Date.now
}
});
module.exports = mongoose.model('Pet', pet_schema);
Insyde an async 方法我构建查询,从对象 filter 获取所有用户输入值,我还有 query 对象,我在其中推送不同的条件并将其与 $and 一起使用/p>
let query = {};
let contentQuery = []
if (filter.public && !filter.private) {
contentQuery.push({ status: { $eq: "public" } });
} else if (filter.privada && !filter.public) {
contentQuery.push({ status: { $eq: "private" } });
}
query = { $and: contentQuery }
try {
const publication = await Publication.find(query).populate('pet');
} catch (e) {
console.log(e)
}
问题是当我想添加更多标准时:
if (filter.specie) { // for example filter.specie equals 'cat'
contentQuery.push({ pet: { type: { $eq: filter.specie } } });
}
我得到错误:
'Cast to ObjectId failed for value "{ type: { \'$eq\': \'cat\' } }" at path "pet" for model "Publication"',
name: 'CastError',
stringValue: '"{ type: { \'$eq\': \'cat\' } }"',
kind: 'ObjectId',
value: { type: { '$eq': 'cat' } },
path: 'pet',
reason: undefined,
model: Model { Publication } }
所以。如何查询出版物的字段以及出版物中的宠物字段?
【问题讨论】:
-
您的问题是否意味着您要选择
pet.specie等于cat的出版物?? -
@AliElkhateeb 是的,还有查询的其余部分,例如发布状态以及我的应用程序具有的其他字段
标签: javascript node.js mongodb mongoose