首页 > 解决方案 > 使用节点和猫鼬插入依赖于另一个的文档

问题描述

使用node和mongoose成功插入其他文档后如何插入文档?

示例:我使用 mongoose 运行创建文档,当成功输入后,执行其他创建文档,如果第二个创建文档失败,我在插入之前“取消”。

我的问题是插入相互依赖,如果秒失败,我可以在不删除第一个文档的情况下这样做吗?

标签: javascriptnode.jsmongodbexpressmongoose

解决方案


通过回调方法完成第一个文档插入后,您可以插入第二个文档。检查我下面的例子,

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

推荐阅读