首页 > 解决方案 > 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));
  });

一切正常

标签: node.jsmongoose

解决方案


$in用于查找包含数组的项目,但_id它只是一个 JSON 键/值对。所以你不能使用 $in。如果您的对象看起来像这样,那么您可以使用 $in

 {
    id: [ObjectId("5de64b376c79643fa847e86b"),
         ObjectId("5de64b376c79643fa847e86b")]
 }

推荐阅读