【发布时间】:2020-03-28 07:27:34
【问题描述】:
我正在测试猫鼬查询,我发现了这种奇怪的行为。我有一个带有_id: "5de64b376c79643fa847e86b" 的文档,如果我调用findById 方法,文档就会很好地返回。但是,如果我在集合上调用 find 方法,则将具有相同 ID 值的数组作为 args 而不返回任何内容,而我希望一个元素的数组是文档。总结一下:
mongooseModel.findById(mongoose.Types.ObjectId("5de64b376c79643fa847e86b")) // Works
mongooseModel.find({ _id: { $in: [mongoose.Types.ObjectId("5de64b376c79643fa847e86b")] } }) //Doesn't work
两者有什么区别,为什么第二个不起作用?
编辑:这是访问该方法的代码。 我在 ApolloServer 配置中定义了一个 DataSource
const app = new ApolloServer({
...
dataSources: () => ({
source: new SourceAPI(DocumentModel)
})
...
});
其中 SourceAPI 是 DataSource 类,DocumentModel 是猫鼬模型。
SourceAPI 是这样定义的
class SourceAPI {
async get(ids) {
return await DocumentModel.find({
_id: {
$in: ids
}
});
}
}
现在,在 GraphQL 解析器中,我终于调用 API 方法来获取文档,就像这样
const findResolver = () =>
DocumentSchema.get("$findById").wrapResolve(next => async rp => {
let ids = [];
ids.push(mongoose.Types.ObjectId(rp.args._id));
return await rp.context.dataSources.source.get(ids);
});
其中DocumentSchema 是使用graphql-compose-mongoose 包生成的文档模型的GraphQL Schema。 get("$findById") 和 wrapResolve 方法也来自该包。我所做的是使用这些方法获取 GraphQL 查询参数并将它们传递给 API 方法(在这种情况下,我只是获取一个 ID 进行测试)。
如果我将 API 方法更改为这样的方式
async get(id) {
return await DocumentModel.findById(id);
}
以及解析器方法
const findResolver = () =>
DocumentSchema.get("$findById").wrapResolve(next => async rp => {
return await rp.context.dataSources.source.get(mongoose.Types.ObjectId(rp.args._id));
});
一切正常
【问题讨论】: