Dev Srivastava
Dev Srivastava

Reputation: 99

How to use Mongodb's insertMany operation to insert multiple documents

I am new to Nodejs and I have been assigned a task to insert multiple documents to a collection in database using node and mongodb. I am creating a performance of a user and then I am getting all friends of that user. Now for all the friends, I have to generate a notification object in my database.

Here is my function to generate notification-

function generateNotification(performanceId, allFriends) {
    return new Promise((resolve, reject) => {
        var friendUserIds = []
        var performance = []
        var doc = []

        doc = allFriends.Friends.forEach(function (friend) {
            friendUserIds.push(friend.friendUserId)
            performance.push(performanceId)
        })

        notificationObj.insertMany(doc, (err, notifgenerated) => {
            if (err) {
                reject({ "Success": "0", "Message": "Some error occured" })
            } else {
                var message = { "Success": "1", "Message": "Notification(s) generated", "Notif": notifgenerated }
                resolve(message)
            }
        })
    })
}

Here I am fetching all the friend user id's and storing then in a array. Currently only one object is being inserted and that too without the friendId or performanceId. Now how do I create multiple objects for each friend Id?

Upvotes: 0

Views: 468

Answers (1)

Subburaj
Subburaj

Reputation: 5192

My guess is that you are running your loop wrong: you have to change the loop logic as follows:

var doc = []

allFriends.Friends.forEach(function (friend) {
var obj = {};
    obj.friendId = friend.friendUserId
    obj. performanceId = performanceId;
    doc.push(obj)
})

notificationObj.insertMany(doc, (err, notifgenerated) => {
    if (err) {
        reject({ "Success": "0", "Message": "Some error occured" })
    } else {
        var message = { "Success": "1", "Message": "Notification(s) generated", "Notif": notifgenerated }
        resolve(message)
    }
})

Upvotes: 1

Related Questions