Kevin Kevin - 3 months ago 25
Node.js Question

How to insert array to mongodb using node.js

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();
});
});
}
});
});
});

Answer

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();
                    });
                });
            });
        });
    }
});
Comments