我正在MongoDB领域中编写一个函数,我想使用它作为GraphQL的自定义解析器。函数的一部分应该通过其id获得特定的文档。根据文档,我可以使用context.services.get('mongodb-atlas')访问阿特拉斯数据库。以下是简化的代码摘录:
exports = async () => {
const cluster = context.services.get('mongodb-atlas');
const collection = cluster.db('my-db').collection('my-coll');
return await collection.findOne({"_id": "61d33d2059c38ef0584c94f8"});
}但是,findOne()调用返回null。我知道上面的id是有效的,因为我可以成功地调用collection.find()并列出所有的文档及其id。
我试过的
findOne({"_id": "61d..."}) -返回nullfindOne({"_id": new ObjectId("61d...")}) -错误:" ObjectId“不是defined.const ObjectId = require('mongodb').ObjectId声明ObjectId为推荐的here -错误:"MongoDB Node.js驱动程序不是supported".const ObjectId = require('bson').ObjectId - findOne()再次返回null。你能推荐其他途径来做这个查找吗?
发布于 2022-03-26 16:30:10
我建议的第一件事是-让我们确定脚本失败的地方。我们可以肯定地知道,下面这些应该是可行的。
exports = async () => {
let tmp_collection = context.services.get("mongodb-atlas").db("my-db").collection("my-coll");
return await tmp_collection.findOne({});
}在您确认上面的工作之后,尝试一下:
return await context.services.get("mongodb-atlas").db("my-db").collection("my-coll").findOne({"_id":new BSON.ObjectId("61d33d2059c38ef0584c94f8")});这是您的代码,但已修复:
exports = async () => {
const cluster = context.services.get('mongodb-atlas');
const collection = cluster.db('my-db').collection('my-coll');
return await collection.findOne({"_id": new BSON.ObjectId("61d33d2059c38ef0584c94f8")});
}https://stackoverflow.com/questions/70597332
复制相似问题