Ad

Insert Documents Dependent On The Other With Node And Mongoose

How can I insert a document after other documents is inserted successfully with node and mongoose?

Examples: I run a create document with mongoose and when this is entered successfully, execute other create document, if this second create document fails, i "cancel" before inserts.

My problem is the inserts depend on each other, can i do thisn without delete first document if seconds fails ?

Ad

Answer

You can just insert the second document once the first document insertion is completed via the callback method. Check my example below,

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";

//creating database connection
MongoClient.connect(url, function(err, db) {
  if (err) throw err;

  var dbo = db.db("mydb"); // Your database name

  var myobj = { name: "Company Inc", address: "Highway 37" }; //first document

  dbo.collection("customers").insertOne(myobj, function(err, firstDocumentId) {
    if (err) throw err; //error while inserting first document

    // first insertion successful
    console.log("1 document inserted in customer table");

    //second document
    var logObj = { msg: "First Document Created", firstDocumentId: firstDocumentId }; //second document

    dbo.collection("logs").insertOne(logObj, function(err, secondDocumentId) {
       if (err) {
           console.log("second document insertion failed");
           dbo.collection("customers").remove({_id:firstDocumentId});       
           throw err;
       }
       console.log("2 document inserted in logs table");
       db.close();
    });
  });
});
Ad
source: stackoverflow.com
Ad