【问题标题】:Mongoose find and findById inconsistencyMongoose find 和 findById 不一致
【发布时间】: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));
  });

一切正常

【问题讨论】:

    标签: node.js mongoose


    【解决方案1】:

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

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

    【讨论】:

    • 尝试这样做return DocumentModel.find({ _id: [mongos.Types.ObjectId(id)] }); 同样的结果,没有找到文件
    • 你为什么使用[ ]
    猜你喜欢
    • 1970-01-01
    • 2013-12-04
    • 2020-05-13
    • 1970-01-01
    • 2018-09-16
    • 2018-06-11
    • 2015-02-12
    • 2015-02-04
    相关资源
    最近更新 更多