我為從 Express JS 洗掉 MongoDB 中的檔案所付出的努力感到震驚。我發現檔案和方法的組合包括 deleteOne、findByIdAndRemove,一些教程說你需要宣告一個 ObjectId,而有些則不需要。瘋狂。
無論如何,下面是我的代碼。我有一個連接資料庫的函式:
const withDB = async (operations, res) => {
try {
const client = await MongoClient.connect('mongodb://localhost:27017', { useNewUrlParser: true });
const db = client.db('database-name');
await operations(db);
client.close();
} catch (error) {
res.status(500).json({ message: 'Error connecting to db', error });
}
}
然后下面是我的洗掉命令:
app.delete('/api/reports/delete-report/:id', async (req, res) => {
//call withDB function above
withDB(async (db) => {
//delete command
const result = await db.collection('reports').deleteOne( { _id : new MongoClient.ObjectId(req.params.id) } );
//get reports
const reportInfo = await db.collection('reports').find().toArray()
//put returned reports into the result provided
res.status(200).json(reportInfo);
}, res);
});
對于我的麻煩,我收到訊息“連接到資料庫時出錯”。如果我執行洗掉命令:
const result = await db.collection('reports').deleteOne( { _id : req.params.id } );
我只是得到了回傳的資料庫內容,但沒有洗掉。
uj5u.com熱心網友回復:
問題是:
new MongoClient.ObjectId(req.params.id)
您不想創建另一個 mongoclient。它需要是
new ObjectId(req.params.id)
并確保您匯入該類:
const { MongoClient, ObjectId } = require('mongodb');
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/372925.html
