MongoJS 不按 ID 删除

MongoJS Not Deleting By ID

 async deleteRecipeById(recipeId){
    try{
        const client = new MongoClient(this.uriString);
        
        await client.connect();
        const db = client.db(this.databaseString);
        const recipeCollection = db.collection(this.collectionString);

        //console.log(await recipeCollection.find({recipeName:recipeName}).toArray());
        var recipeIdAsObject = new ObjectId(recipeId);
        var result = recipeCollection.deleteMany({"_id":recipeIdAsObject});
        client.close();
        return result;
    }
    catch(e){
        console.error(e);
    }
}

我正在测试我的 mongo 驱动程序,但我终其一生都无法弄清楚为什么它不起作用。我 运行 对我的 deleteRecipeByName() 进行了相同的测试并且测试通过了。所以这对我来说表明我的测试装置很好。这意味着我知道数据库中存在具有正确 ID 的食谱。

在我 运行 测试之前,我什至调用了一个我已经测试过的 getRecipeByName 函数,以确保食谱与我正在寻找的 ID 存在,这就是结果。

[
{
  _id: 0,
  recipeName: 'mock0',
  recipeIngredients: [ 'i0', 'i1', 'i2' ]
}
]

还有我的测试函数

describe('Testing delete Recipe',()=>{
it('1. Delete known recipe',(done)=>{
    var uri = "mongodb://localhost:27017";
    var dbname = "testRecipes";
    var collectionName = "testCollectionMessy";
    let driver = new MongoDriver(uri,dbname,collectionName);
    driver.dropCollection().then(()=>{//Clean collection for testing... NEVER CALL ON PRODUCTION COLLECTION
        driver.addMockData().then((p)=>{
            driver.getRecipeById(mockData[0]._id).then((p)=>{
                console.log(p);
            })
            driver.deleteRecipeById(0).then((p)=>{
                console.log(p);
                console.log(mockData[0]._id);
                assert.deepEqual(p.deletedCount,1);
                done();
            }).catch((e)=>{
                console.log(e);
                done(e);
            })
        });
    }); 
})
})

这是我从 JSON

导入的模拟数据
[
 {"_id":0,"recipeName":"mock0","recipeIngredients":["i0","i1","i2"]},
 {"_id":1,"recipeName":"mock1","recipeIngredients":["i0","i1","i2"]},
 {"_id":2,"recipeName":"mock2","recipeIngredients":["ingredient"]}
]

问题在于如何管理 receipeId。

如果 ID 不是有效的 mongo 对象 ID,

new ObjectId(id) 将抛出,因此您可以添加一个片段来管理两种格式,如下所示:

 async deleteRecipeById(recipeId){
    try{
        const client = new MongoClient(this.uriString);
        
        await client.connect();
        const db = client.db(this.databaseString);
        const recipeCollection = db.collection(this.collectionString);

        var recipeIdAsObject;
        if(/^(?=[a-f\d]{24}$)(\d+[a-f]|[a-f]+\d)/i.test(recipeId)){
           recipeIdAsObject = new ObjectId(recipeId);
        } else {
           recipeIdAsObject = recipeId
        }

        var result = recipeCollection.deleteMany({"_id":recipeId});
        client.close();
        return result;
    }
    catch(e){
        console.error(e);
        // it is dangerous to ignore errors
    }
}

我建议只选择一种格式,否则很难跨应用程序进行查询。