2

I want to insert array of document to mongodb using node.js but while inserting it's only inserting first data only.

[{
  "userid": "5664",
  "name": "Zero 2679",
  "number": "1234562679",
  "status": "contact",
  "currentUserid": "Abcd"
 }, 
 {
  "userid": "5665",
  "name": "Zero 3649",
  "number": "1234563649",
  "status": "contact",
  "currentUserid": "Xyz"
}]

Sample code

collection.insert([{"userid": userid,"name": name,"number": number,"status": status,"currentUserid": currentUserid}], function(err, docs) {
    if (err) {
        res.json({error : "database error"});
    }else {
       collection.find({currentUserid:currentUserid}).toArray(function(err, users) {
          res.send(users);
       });
    }});

But it still inserting first value only can you please tell me how to insert all these documents.

Please kindly go through my post and suggest me some solution.

1 Answer 1

5

In your sample code you are adding only 1 user.

db.collection('myCollection').insert([doc1, doc2]); inserts two documents using bulk write.

See documentation here: https://docs.mongodb.org/manual/reference/method/db.collection.insert/

From your sample, you can do:

var data = [{
  "userid": "5664",
  "name": "Zero 2679",
  "number": "1234562679",
  "status": "contact",
  "currentUserid": "Abcd"
 }, 
 {
  "userid": "5665",
  "name": "Zero 3649",
  "number": "1234563649",
  "status": "contact",
  "currentUserid": "Xyz"
}];
db.collection('myCollection').insert(data)
.then(function() {
  return db.collection('myCollection').find({number: {$in: ["1234563649", "1234562679"]}});
})
.then(function(res) {
  console.log(res);
});
Sign up to request clarification or add additional context in comments.

4 Comments

hey thanks can you update my sample code and tell me how to do that because bulk operation also i have tried but it's inserting only first value
there is also the insertMany method in the vanilla driver.
hey thanks it worked, can you please tell me one thing how to make it dynamic because i am pretty to node.js and mongodb.
'how to make it dynamic': are you talking about the the db.collection('').find?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.