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
.
//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
:
[
{
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?
If i change the code and use mongoose without transactions, I can then call the customer.hello()
method successfully.