Skip to content

Commit

Permalink
Add URL support, fix #247
Browse files Browse the repository at this point in the history
  • Loading branch information
terehov committed Aug 7, 2023
1 parent 4073f60 commit ef3dd47
Show file tree
Hide file tree
Showing 6 changed files with 1,671 additions and 0 deletions.
60 changes: 60 additions & 0 deletions examples/nodejs/mongodb/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { MongoClient } from "mongodb";
import { Logger, ILogObj } from "tslog";

interface ITestData {
_id: string;
testList: string[];
}

const log: Logger<ILogObj> = new Logger();

const dbOperate = async (col: any, id: string, testId: string) => {
const firstResult = await col.findOneAndUpdate(
{ _id: id, testList: { $not: { $eq: testId } } },
{
$push: {
testList: {
$each: [testId],
$slice: 10,
},
},
},
{
upsert: true,
projection: { testList: 1 },
returnDocument: "after",
}
);
};

const main = async (): Promise<void> => {
const mongoClient = new MongoClient("mongodb://127.0.0.1:27017", {
family: 4,
noDelay: true,
connectTimeoutMS: 5000,
});

await mongoClient.connect();

const db = mongoClient.db("test");
const col = db.collection<ITestData>("test_col");
const id = "10001";
const testId = "1001";

// delete key may already exist
await col.deleteOne({ _id: id });

// should ok
const firstResult = await dbOperate(col, id, testId);
log.info("first result", firstResult);

try {
const secondResult = await dbOperate(col, id, testId); // trigger duplicate key error
log.info("second result", secondResult);
} catch (error) {
console.log("error", error);
log.error("second result", error); //traceback here
}
};

main();
Loading

0 comments on commit ef3dd47

Please sign in to comment.