Чтобы обновить документ в MongoDB с помощью Node.js на основе его _id, вы можете использовать несколько методов. Вот несколько часто используемых подходов:
-
Использование метода
updateOne:const { MongoClient, ObjectId } = require('mongodb'); async function updateDocumentById() { const client = new MongoClient('<mongodb_connection_string>'); await client.connect(); const collection = client.db('<database_name>').collection('<collection_name>'); const filter = { _id: ObjectId('<document_id>') }; const update = { $set: { /* updated fields */ } }; const result = await collection.updateOne(filter, update); console.log(`${result.modifiedCount} document(s) updated.`); client.close(); } updateDocumentById(); -
Использование метода
findOneAndUpdate:const { MongoClient, ObjectId } = require('mongodb'); async function updateDocumentById() { const client = new MongoClient('<mongodb_connection_string>'); await client.connect(); const collection = client.db('<database_name>').collection('<collection_name>'); const filter = { _id: ObjectId('<document_id>') }; const update = { $set: { /* updated fields */ } }; const result = await collection.findOneAndUpdate(filter, update); console.log(`${result.lastErrorObject.n} document(s) updated.`); client.close(); } updateDocumentById(); -
Использование метода
updateManyдля обновления нескольких документов на основе_id:const { MongoClient, ObjectId } = require('mongodb'); async function updateDocumentsByIds() { const client = new MongoClient('<mongodb_connection_string>'); await client.connect(); const collection = client.db('<database_name>').collection('<collection_name>'); const filter = { _id: { $in: [ObjectId('<id1>'), ObjectId('<id2>'), /* ... */] } }; const update = { $set: { /* updated fields */ } }; const result = await collection.updateMany(filter, update); console.log(`${result.modifiedCount} document(s) updated.`); client.close(); } updateDocumentsByIds();
Не забудьте заменить , , и с соответствующими значениями, специфичными для вашей настройки MongoDB.