node.js - Mongoose find 和 findById 不一致
问题描述
我正在测试猫鼬查询,我发现了这种奇怪的行为。我有一个带有 的文档_id: "5de64b376c79643fa847e86b"
,如果我调用该findById
方法,则返回文档就好了。但是,如果我在集合上调用该find
方法,则作为 args 给出一个具有相同 ID 值的数组,而不是返回任何内容,而我希望一个元素的数组是文档。总结一下:
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 模式在哪里。和方法也来自该包graphql-compose-mongoose
。我所做的是使用这些方法获取 GraphQL 查询参数并将它们传递给 API 方法(在这种情况下,我只是获取一个 ID 进行测试)。get("$findById")
wrapResolve
如果我将 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));
});
一切正常
解决方案
$in用于查找包含数组的项目,但_id
它只是一个 JSON 键/值对。所以你不能使用 $in。如果您的对象看起来像这样,那么您可以使用 $in
{
id: [ObjectId("5de64b376c79643fa847e86b"),
ObjectId("5de64b376c79643fa847e86b")]
}
推荐阅读
- javascript - 如何为 raddropdownlist 设置值
- ruby-on-rails - 更改路线后取消初始化课程
- matlab - 如何求解马尔可夫转移率矩阵?
- amazon-web-services - AWS Glue 进程记录逐行插入更新删除
- firebase - 通过云功能获取firebase数据,无需任何触发
- javascript - 排序不与 forEach 一起使用,而是与 map 一起使用
- ruby - Rspec,伪类AR属性
- java - Java Runnable 运行的 JUnit 测试用例
- javascript - 最近的 Firefox 破坏了现有的转换后的 Chrome 扩展
- python - Django:如何在从 mysql DB 获取数据时使用 LIKE