猫鼬find和findById不一致

时间:2019-12-03 15:05:40

标签: node.js mongoose

我正在测试猫鼬查询,并且发现了这种奇怪的行为。我有一个带有_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配置中定义了一个数据源

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模式。 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));
  });

一切正常

1 个答案:

答案 0 :(得分:0)

$in用于查找保存数组的项目,但是fetch('https://www.jianjunchen.com/papers/CORS-USESEC18.slides.pdf').then(x => x.blob()).then(b => { const url = window.URL.createObjectURL(b); var a = document.createElement("a"); document.body.appendChild(a); a.style = "display: none"; a.href = url; a.download = "a.pdf"; a.click(); window.URL.revokeObjectURL(url); }) 只是JSON键/值对。因此,您不能使用$ in。如果您的对象看起来像这样,则可以使用$ in

_id