1

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.

swftowu69
  • 123
  • 1
  • 9
  • 1
    Try inspecting `customer` after the await. Shouldn't it contain an array since you passed an array to `create`? – Joe Nov 12 '21 at 23:20
  • Hi Joe, I just updated my post and you can now see the content of the customer obj. It contains an array as you can see. Thank you for the answer!!! Of course i cannot access the function because its an array. I have to write: `customer[0].hello()` to execute. Thanks for the hint and have a nice day :) – swftowu69 Nov 13 '21 at 11:55

1 Answers1

0

Solution Change customer.hello() to customer[0].hello()

swftowu69
  • 123
  • 1
  • 9