I've two async functions, which are async function start(){} & async function end(){}
So in both functions I'm having mongodb operations. I want to send document id generated inside start() function to the end() function and then log it there.
This is my start function:
async function start() {
await client.connect();
const db = client.db(dbName);
const col = db.collection("mongotroncol");
let personDocument = {
"name" : "shubham"
}
// Insert a single document, wait for promise so we can read it back
const p = await col.insertOne(personDocument);
const abc = p.insertedId;
const docid = abc.toString()
return docid;
}
and then I've this end() function and I'm trying to send unique docid generated in start() function to the end() function with returning that value & log it in end() function as follows:
async function end() {
mongoid = await start();
console.log(mongoid);
}
So for example "623cb515366c70a2a3c27288" this is my document id generated in start() function then what I desire is to console.log this same id in end() function but as I'm writing await start() in end() function, again start() function is called & run, result of which new mongodb document id is generated and new one is logged but I want the doc id generated from start() only.
One important point: I've two events which are app.on('ready') & app.on('quit') so I'm calling await start() & await end() respectively like this:
app.on('ready', () => {
await start();
});
and
app.on('quit', () => {
await end();
});
So my 1st button click will trigger app.on('ready') event which will run async start() function and generate a mongodb document with unique docid and then on my 2nd button click(which I'll do after some minutes) will trigger app.on('quit') which will run async end() function & ideally I want the same docid generated in async start() function but I'm getting "623cb515366c70a2a3c27289" which is exactly one bit incremented than the generated in start() function [please see the id value mentioned in the earlier paragraph] So the concern is to get same docid. Thank you!!
So after a bit brainstorming I tried one approach & it worked.
I declared a global variable as let doc_id = "";
Then in start() function I just assigned a value to doc_id like this:
async function start() {
await client.connect();
const db = client.db(dbName);
const col = db.collection("mongotroncol");
let personDocument = {
"name" : "shubham"
}
const p = await col.insertOne(personDocument);
doc_id = p.insertedId.toString();
}
And now at the time of calling the end() function I did this:
app.on('quit', () => {
await end(doc_id);
});
async function end(doc_id) {
console.log(doc-id);
}