我可以看到這個問題應該在這里得到回答,但是代碼根本不適合我(我嘗試了多種類似的變體)。
這是我的資料:
[{
"_id": {
"$oid": "628cadf43a2fd997be8ce242"
},
"dcm": 2,
"status": true,
"comments": [
{
"id": 289733,
"dcm": 2,
"status": true,
"clock": "158",
"user": "Nathan Field",
"dept": "IT",
"department": [],
"dueback": "",
"comment": "test 1"
},
{
"id": 289733,
"dcm": 2,
"status": true,
"clock": "158",
"user": "Nathan Field",
"dept": "IT",
"department": [],
"dueback": "",
"comment": "test 2"
}
],
"department": [],
"dueback": ""
}]
這是我的代碼
const deleteResult = await db.collection('status').updateOne(
{ "dcm": comments.dcm },
{ $pull: { "comments": { "id": comments.id } } },
{ upsert: false },
{ multi: true }
);
絕對什么都不會發生...
uj5u.com熱心網友回復:
所以這個問題最終與在一個函式中運行多個更新操作有關。我有一個這樣的資料庫連接功能:
const withDB = async (operations, res) => {
try {
const client = await MongoClient.connect('mongodb://localhost:27017', { useNewUrlParser: true });
const db = client.db('collection');
await operations(db);
client.close();
} catch (error) {
res.status(500).json({ message: 'Error connecting to db', error });
}
}
然后我使用以下方法呼叫它:
withDB(async (db) => {
await db.collection('status').updateMany(
{ "dcm": comments.dcm },
{ $pull: { "comments": { "id": comments.id } } },
{ multi: true }
);
});
出現這個問題似乎是因為我在一個withDB函式中有兩個這樣的更新操作。我在其他實體中有多個操作(更新專案,然后獲取集合),但由于某種原因,這導致了一個問題。
我創建了對withDB函式的單獨呼叫來執行“$pull”(洗掉)請求,然后使用新注釋更新陣列。
為了檢查我的實際查詢沒有問題,我使用了 Studio3T 的 IntelliShell 功能。如果我早點這樣做,我會為自己節省很多時間!
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/491512.html
