[英]NodeJS Mongoose with Transactions | Can't find Schemafunction
I have here the following non-working minimalexample where i want to call customer.hello()
but I will get an TypeError: customer.hello is not a function
.我在这里有以下非工作最小示例,我想在其中调用customer.hello()
但我会得到一个TypeError: customer.hello is not a function
。
//app.js
require("dotenv").config();
const mongoose = require('mongoose');
const Customer = require('./models/Customer');
const start = async () => {
const db = await mongoose.connect(process.env.MONGO_URI);
const session = await db.startSession();
try {
session.startTransaction();
const customer = await Customer.create([{ firstName: "john" }], { session: session });
customer.hello(); //TypeError: customer.hello is not a function
await session.commitTransaction();
} catch (error) {
console.error(error);
await session.abortTransaction();
}
finally {
session.endSession();
}
};
start();
The customer
object after the await customer.create
: await customer.create
之后的customer
对象:
[
{
firstName: 'john',
_id: new ObjectId("618fa6b968e8419bbf7ee952"),
__v: 0
}
]
//Customer.js
const mongoose = require('mongoose');
const CustomerSchema = new mongoose.Schema({ firstName: { type: String } });
CustomerSchema.methods.hello = function () {
console.log('helloprint');
return "hello";
}
module.exports = mongoose.model('Customer', CustomerSchema);
Why is customer.hello
not a function?为什么customer.hello
不是函数? If i change the code and use mongoose without transactions, I can then call the customer.hello()
method successfully.如果我更改代码并在没有事务的情况下使用 mongoose,我就可以成功调用customer.hello()
方法。
解决方案 将customer.hello()
改为customer[0].hello()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.