node.js - 在 mongoose 中使用事务会引发错误
问题描述
从这篇 SO 帖子中得到启发,我尝试使用 Mongoose 5.2.13 实现 MongoDB 的新事务功能。这是我的尝试:
addPost: async (parent, args) => {
// Add new post to dbPosts
const session = await dbPost.startSession();
session.startTransaction();
try {
const opts = { session };
const q1 = await dbPost({
_id: new mongoose.Types.ObjectId(),
title: args.title,
content: args.content,
author: {
id: args.author_id,
first_name: args.author_first_name,
last_name: args.author_last_name,
}
}).save(opts);
const q2 = await dbUser.findOneAndUpdate(
{_id: args.author_id},
{$push: {posts:
{
id: 'a14def', // need access to the _id field from q1
title: args.title,
content: args.content,
}
}},
opts);
await session.commitTransaction();
session.endSession();
} catch(err) {
await session.abortTransaction();
session.endSession();
console.log('ERRORS:\n-----------\n' + err);
console.log('\n------------\n\n');
throw err;
}
}
但是,运行上面的代码会返回以下错误:
BSON 字段“insert.autocommit”是一个未知字段。
这是什么意思,我的代码的哪一部分导致了它?另外,如何访问第一个操作(在这种情况下)生成的_id.save()
以用于第二个操作(.findOneAndUpdate()
在这种情况下)?目前,我只是在那里硬连线一个虚拟值:
id: 'a14def'
解决方案
推荐阅读
- android - 如何在不单击的情况下将特定的 ListView 项目位置获取到 TextView
- json - TypeError:“dict”对象在 Python 中不可调用
- java - 结合 jsonpath 表达式读取 json 字符串中的 2 个嵌套属性
- ios - 我们如何在 Swift (StoryBoard) 中通过 UITableViewController 创建自定义视图?
- python - 我可以在 python 中使用 rust 的匹配项吗?
- python - 使用 setup.py setuptools 安装到 venv
- javascript - 通过将鼠标悬停附加到圆圈,鼠标悬停在 d3.js 中不起作用
- angular - 我想从数组中获取对象的值
- google-chrome-os - Crostini 在另一台计算机上查看本地主机
- mysql - 事情在本地主机上工作,但没有服务器端出现错误:PHP 和 MySQL 的内部错误 500