My request is quite simple:
I need to add a new document to my MongoDB database. However, before doing so, I must first check if the slug
already exists in the database. If it does, I need to rename the slug before proceeding with the insertion.
I have been attempting to utilize an async await
call to verify the existence of the slug
and then insert the document accordingly.
mongoClient.connect(function (err, mongoClient) {
let db = mongoClient.db("articles");
let categoryCheck = async (db, category_info) => {
let slugCheck = await db.collection('categories').find({slug: category_info.slug});
slugCheck.count((err, count) => {
if (count > 0) {
let newSlug = `${category_info.slug}_${new Date().getTime()}`;
console.log(newSlug);
return newSlug;
}
else
return category_info.slug;
})
};
let categoryPromise = categoryCheck(db, category_info);
categoryPromise.then(value => {
console.log(value);
category_info.slug = value;
});
db.collection('categories')
.insertOne(category_info, (err, data) => {
assert.equal(null, err);
res.status(200);
res.json('success');
});
mongoClient.close();
});
The console displays an undefined
value from the Promise
. Could you please assist me in resolving this issue?
I am still learning the ropes of MongoDB
. Is there a more efficient way to handle these two queries together in a single query?
Thank you!