javascript - 使用节点和猫鼬插入依赖于另一个的文档
问题描述
使用node和mongoose成功插入其他文档后如何插入文档?
示例:我使用 mongoose 运行创建文档,当成功输入后,执行其他创建文档,如果第二个创建文档失败,我在插入之前“取消”。
我的问题是插入相互依赖,如果秒失败,我可以在不删除第一个文档的情况下这样做吗?
解决方案
通过回调方法完成第一个文档插入后,您可以插入第二个文档。检查我下面的例子,
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();
});
});
});
推荐阅读
- java - 在 Android 中的绘制/布局操作错误期间避免对象分配
- java - 如何检查我的 firebaseUser 是否包含任何 displayName?
- transactions - Websphere 上设置的事务超时
- python - 没有返回记录时的MySQL存储过程
- python - 将迭代保存在不同的 CSV 文件中
- c++ - 比较两个 std::chrono::time_point 实例时出错
- java - Android Studio 4 无法检测到 java 代码并且无法打开 SDK 管理器、设置
- django - 如何使用 Django 将此 if 语句添加到模板并改进 views.py
- r - 带有colnames的素食错误的adonis函数
- shell - shell中的十进制算术显示为找不到命令