|
| 1 | +import { MongoClient } from "mongodb"; |
| 2 | +import { Logger, ILogObj } from "tslog"; |
| 3 | + |
| 4 | +interface ITestData { |
| 5 | + _id: string; |
| 6 | + testList: string[]; |
| 7 | +} |
| 8 | + |
| 9 | +const log: Logger<ILogObj> = new Logger(); |
| 10 | + |
| 11 | +const dbOperate = async (col: any, id: string, testId: string) => { |
| 12 | + const firstResult = await col.findOneAndUpdate( |
| 13 | + { _id: id, testList: { $not: { $eq: testId } } }, |
| 14 | + { |
| 15 | + $push: { |
| 16 | + testList: { |
| 17 | + $each: [testId], |
| 18 | + $slice: 10, |
| 19 | + }, |
| 20 | + }, |
| 21 | + }, |
| 22 | + { |
| 23 | + upsert: true, |
| 24 | + projection: { testList: 1 }, |
| 25 | + returnDocument: "after", |
| 26 | + } |
| 27 | + ); |
| 28 | +}; |
| 29 | + |
| 30 | +const main = async (): Promise<void> => { |
| 31 | + const mongoClient = new MongoClient("mongodb://127.0.0.1:27017", { |
| 32 | + family: 4, |
| 33 | + noDelay: true, |
| 34 | + connectTimeoutMS: 5000, |
| 35 | + }); |
| 36 | + |
| 37 | + await mongoClient.connect(); |
| 38 | + |
| 39 | + const db = mongoClient.db("test"); |
| 40 | + const col = db.collection<ITestData>("test_col"); |
| 41 | + const id = "10001"; |
| 42 | + const testId = "1001"; |
| 43 | + |
| 44 | + // delete key may already exist |
| 45 | + await col.deleteOne({ _id: id }); |
| 46 | + |
| 47 | + // should ok |
| 48 | + const firstResult = await dbOperate(col, id, testId); |
| 49 | + log.info("first result", firstResult); |
| 50 | + |
| 51 | + try { |
| 52 | + const secondResult = await dbOperate(col, id, testId); // trigger duplicate key error |
| 53 | + log.info("second result", secondResult); |
| 54 | + } catch (error) { |
| 55 | + console.log("error", error); |
| 56 | + log.error("second result", error); //traceback here |
| 57 | + } |
| 58 | +}; |
| 59 | + |
| 60 | +main(); |
0 commit comments