I have a list called collectionList
, and I am wanting to go through the object list and see if a document in my mongodb collection exists. If it doesn’t exist, then it will create a new document for that list item. The new document name
should be the same as the name
in the object list.
Here is the list:
const collectionList = [
{ name: "pages", schema: pageSchema.pageSchema },
{ name: "posts", schema: postSchema.postSchema }
]
If there is not a document with the name
equal to the collectionList[i].name
, then I want mongoose to create a new document with the name
.
Here is the section of the code that the bug is occurring in:
for (var i = 0; i < collectionList.length; i++) {
var collectionName = collectionList[i].name
console.log("collectionList name:",collectionName); // Outputs the collectionList[i].name to make sure it is working
Collection.countDocuments({ name: collectionName })
.then((data) => {
console.log(data)
if (data == null || data == 0 || data == false) {
const newCollection = new Collection({
name: collectionName,
data: []
})
newCollection.save().then(() => {
console.log('collection saved', collectionName)
}).catch((err) => {
console.log(err)
})
} else {
console.log("I found it, but I don't know what to do!")
}
}).catch((err) => {
console.log(err)
})
}
My mongodb collection is called Collection
and it is empty, there are no documents in it. When I run it, it console logs collectionList name: pages
then collectionList name: posts
on line 3. When I look in my mongodb collection, the name
in both document is posts
. Why is it not creating the document with the name: pages
? On line 13 when I console log the collectionName
, both times it logs posts
.
2
Answers
I figured it out. I just needed to add
await
before theCollection.countDocuments({ name: collectionName })
. Like this:await Collection.countDocuments({ name: collectionName })
.just correction and opinion:
its a bit confused to use
await
andthen
in the same time.then
its already promise. and please check the conditionalif (data == null || data == 0 || data == false) {
. useif(data)
instead.following your description, you just need to use
findAndUpdate
, reff findOneAndUpdateif data not exist, then create a new one
.that would be like:
or you can use BulkWrite and
updateOne
for better approachthat would be like: