How to insert array to mongodb using node.js

Kevin

I have an array like [ 570dec75cf30bf4c09679deb, 56fe44836ce2226431f5388f ]. Now I want insert this for new collection named notifications like

{
  "_id": ObjectId("57bd39c9734ff3602a312b33"),
  "userId": ObjectId("570dec75cf30bf4c09679deb") 
}

and

{
  "_id": ObjectId("57bd39c8734ff3602a312b32"),
  "userId": ObjectId("56fe44836ce2226431f5388f ") 
}

I have written a query in node.js to insert this but it inserting last element of array two times like this

{
  "_id": ObjectId("57bd39c9734ff3602a312b33"),
  "userId": ObjectId("56fe44836ce2226431f5388f ") 
}

and

{
  "_id": ObjectId("57bd39c8734ff3602a312b32"),
  "userId": ObjectId("56fe44836ce2226431f5388f ") 
}

The query I have written like this

app.js

router.post('/creatList', function(req,res){
    console.log(req.body.email);
    var emails = req.body.email;

    if(req.body.wData.wishListType == 'Shared'){
        var findUsers = function(db, callback) {
            var cursor;
            cursor = db.collection('users').find({email: { $in: emails }})

            cursor.toArray(function(err, docs){
                if(err){
                    callback(new Error("Some problem"));
                } else {
                    callback(null,docs);
                } 
            });     
        };

        MongoClient.connect(config.database, function(err, db) {
            assert.equal(null, err);
            findUsers(db, function(err,docs) {
                db.close();
                console.log(docs);

                for(var key in docs){
                    console.log(key);
                    var ids = docs[key]._id;
                    console.log(ids);

                    var insertDocument = function(db, callback) {
                        db.collection('notifications').insert({
                            "userId" : ids,
                        },function(err, result) {
                            assert.equal(err, null);
                            console.log("Inserted a document into the notifications collection.");
                            callback();
                        });
                    };

                    MongoClient.connect(config.database, function(err, db) {
                        assert.equal(null, err);
                        insertDocument(db, function() {
                            db.close();
                        });
                    });
                }
            });
        }); 
      });
Wake

You basically need to remap your results from you users.find() so that they will match your schema for your notifications collection. This should work:

var docsToInsert = docs.map(function (doc) {
        // this assumes your users collection has an _id that you actually want to use as the reference for you notifications.userId field
        // actually, you probably want "return {"userId": ObjectID(doc._id)};" since you are using the native mongodb api
        return { "userId": doc._id };
});

So, simplifying what you have for the rest a bit, it would be:

router.post('/creatList', function (req, res) {
    console.log(req.body.email);
    var emails = req.body.email;

    if (req.body.wData.wishListType == 'Shared') {
        var findUsers = function (db, callback) {
            var cursor;
            cursor = db.collection('users').find({ email: { $in: emails } });

            cursor.toArray(function (err, docs) {
                if (err) {
                    callback(new Error("Some problem"));
                } else {
                    callback(null, docs);
                }
            });
        };

        MongoClient.connect(config.database, function (err, db) {
            assert.equal(null, err);
            findUsers(db, function (err, docs) {
                db.close();
                console.log(docs);

                var docsToInsert = docs.map(function (doc) {
                    // this assumes your users collection has an _id that you actually want to use as the reference for you notifications.userId field
                    // actually, you probably want "return {"userId": ObjectID(doc._id)};" since you are using the native mongodb api
                    return { "userId": doc._id };
                });

                MongoClient.connect(config.database, function (err, db) {
                    assert.equal(null, err);
                    db.collection("notifications").insert(docsToInsert, function (err, result) {
                        if (err) {
                            // handle the err however you like 
                            throw err;
                        }
                        db.close();
                    });
                });
            });
        });
    }
});

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to INSERT dynamic info in MySQL table using Node/Express JS

How to insert into MongoDB array

How to insert array of objects into MongoDB using Go

How to do Bulk insert using Sequelize and node.js

Find the document and insert value into array in MongoDB using Node.JS Mongoose

How to insert Javascript's Arraybuffer to mongodb via Node.js

How to display array in frontend using EJS in Mongodb Node js?

How to rename the columnname in mongodb using node js

How to insert a long/BigInt with Node.js MongoDB Driver?

How to insert or update an a array in MongoDB with Node.Js?

insert array into mongodb using pymongo

Append an array using express, Node.js and MongoDB

How to insert json array object in mysql diffrent columns using node js

Manipulating Mongoose/MongoDB Array using Node.js

Nested insert in Mongodb with Node.js

Fail to insert JSON into mongoDB using mongoose in Node.js

How to insert an array multiple times in mongoDB using the Node.js driver?

how to insert new object in node js array if key not exist

how to insert and update data into postgresql from node js using if condition

How can I extract data as object not array from MongoDB using Node.js/Express?

node.js to insert into mongodb

How can insert loop for check each value in array [mongoDB,Node.js]

How to compare mongoDB ObjectIds & remove duplicates in an array of documents using node.js?

Failure to find mongodb array using node.js

update the nested array in mongodb using node js

saving array type value inside mongodb schema using node js

Insert Hour and Minute to mongoDB date in node js

how can insert array consisting of multiple objects using sequelize and node?

How can I insert attributes of an object from an array of objects into SQLServer using Node JS?