我正在使用 mongoose 测试事务,并尝试使用以下代码完成一项非常简单的任务:
const session = await mongoose.startSession();
session.startTransaction();
try {
const opts = { session, new: true };
const A = await Author.
create({
firstName: 'Jon',
lastName: 'Snow'}, session);
if(!A) throw new Error('Aborted A by Amit!');
const B = await Author.
findOneAndUpdate({firstName: 'Bill'}, {firstName: 'William'}, opts);
if(!B) throw new Error('Aborted B by Amit!');
await session.commitTransaction();
session.endSession();
} catch (err) {
await session.abortTransaction();
session.endSession();
throw err;
}
我要做的就是首先插入(使用 Mongoose create()
方法)一个新文档到集合中,然后编辑(使用 Mongo findOneAndUpdate()
方法)同一集合中的另一个文档。任一查询失败都需要中止整个事务套件。
似乎是 create()
给我带来了问题。该文档确实被创建并插入,但是,它也会引发错误:
"Author validation failed: lastName: Path
lastName
is required., firstName: PathfirstName
is required."
知道这意味着什么吗?尽管我已经给了它,但它似乎在提示没有为 required
字段(firstName
和 lastName
)提供值。
最佳答案
I have no idea why it would complain about missing values when I've provided them both and they're still getting added to the collection!
这是因为 Model.create()第一个参数接受要插入的文档,作为数组或作为传播。例如,这两个是等价的:
// pass a spread of docs
Candy.create({ type: 'jelly bean' }, { type: 'snickers' })
// pass an array of docs
Candy.create([{ type: 'jelly bean' }, { type: 'snickers' }])
您的行的问题在于,它试图将第二个文档 {session: session}
作为 Author
的另一个条目,该条目缺少所需的 firstName
和 lastName
字段。
你应该这样做:
Author.create([{ firstName: 'Quentin', lastName: 'Tarantino' }],
{ session: session }
);
您还可以找到 Transactions in Mongoose一个有用的引用。
关于mongodb - 在 Mongoose 事务中使用 `create()` 的验证错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54831245/