【问题标题】:NodeJS Mongoose with Transactions | Can't find SchemafunctionNodeJS Mongoose 与事务 |找不到架构函数
【发布时间】:2021-12-25 00:22:16
【问题描述】:

我在这里有以下不工作的最小示例,我想调用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();

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);

为什么customer.hello 不是函数? 如果我更改代码并使用没有事务的猫鼬,我可以成功调用customer.hello() 方法。

【问题讨论】:

  • 在等待之后尝试检查customer。既然您将数组传递给create,它不应该包含一个数组吗?
  • 嗨,乔,我刚刚更新了我的帖子,您现在可以看到客户 obj 的内容。如您所见,它包含一个数组。谢谢你的回答!!!当然我无法访问该函数,因为它是一个数组。我必须写:customer[0].hello() 才能执行。感谢您的提示,祝您有愉快的一天:)

标签: node.js mongodb mongoose transactions undefined-function


【解决方案1】:

解决方案customer.hello() 更改为 customer[0].hello()

【讨论】:

    猜你喜欢
    • 2021-06-15
    • 2022-06-11
    • 2018-04-16
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 2017-03-16
    • 1970-01-01
    相关资源
    最近更新 更多