简体   繁体   中英

How to insert array of document in mongodb using node.js?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM