Node.js Mongoose find和findById不一致
我正在测试猫鼬查询,我发现了这种奇怪的行为。我有一个id为“5de64b376c79643fa847e86b”的文档Node.js Mongoose find和findById不一致,node.js,mongoose,Node.js,Mongoose,我正在测试猫鼬查询,我发现了这种奇怪的行为。我有一个id为“5de64b376c79643fa847e86b”的文档,如果调用findById方法,文档会很好地返回。但是,如果我调用集合上的find方法,将返回一个ID值与nothing值相同的数组作为args,而我希望文档是一个包含一个元素的数组。总结如下: mongooseModel.findById(mongoose.Types.ObjectId("5de64b376c79643fa847e86b")) // Works mongoose
,如果调用findById
方法,文档会很好地返回。但是,如果我调用集合上的find
方法,将返回一个ID值与nothing值相同的数组作为args,而我希望文档是一个包含一个元素的数组。总结如下:
mongooseModel.findById(mongoose.Types.ObjectId("5de64b376c79643fa847e86b")) // Works
mongooseModel.find({ _id: { $in: [mongoose.Types.ObjectId("5de64b376c79643fa847e86b")] } }) //Doesn't work
这两者有什么区别,为什么第二个不起作用
编辑:这是访问该方法的代码。
我在服务器配置中定义了一个数据源
const app = new ApolloServer({
...
dataSources: () => ({
source: new SourceAPI(DocumentModel)
})
...
});
其中SourceAPI是数据源
类,文档模型
是mongoose模型。
SourceAPI
的定义如下
class SourceAPI {
async get(ids) {
return await DocumentModel.find({
_id: {
$in: ids
}
});
}
}
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);
});
async get(id) {
return await DocumentModel.findById(id);
}
现在,在GraphQL解析器中,我最终调用API方法来获取文档,如下所示
class SourceAPI {
async get(ids) {
return await DocumentModel.find({
_id: {
$in: ids
}
});
}
}
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);
});
async get(id) {
return await DocumentModel.findById(id);
}
其中DocumentSchema
是使用包生成的文档模型的GraphQL模式。get(“$findById”)
和wrapResolve
方法也来自该包。我所做的是使用这些方法获取GraphQL查询参数并将它们传递给API方法(在本例中,我只是获取一个ID进行测试)
如果我把API方法改成这样
class SourceAPI {
async get(ids) {
return await DocumentModel.find({
_id: {
$in: ids
}
});
}
}
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);
});
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));
});
一切正常用于查找包含数组的项,但\u id
只是一个JSON键/值对。因此,您不能在中使用$。如果对象看起来像这样,那么可以在中使用$
{
id: [ObjectId("5de64b376c79643fa847e86b"),
ObjectId("5de64b376c79643fa847e86b")]
}
尝试执行此操作返回DocumentModel.find({u id:[mongos.Types.ObjectId(id)]})代码>相同的结果,没有找到文档为什么要使用[]
?