sequelize.js - aexmachina/factory-girl(节点)无法将工厂与非持久模型关联起来

标签 sequelize.js factory-bot

我试图将工厂模型与非持久模型相关联,但出现错误:

     TypeError: model.get is not a function
      at SequelizeAdapter.get (node_modules/src/adapters/DefaultAdapter.js:13:18)
      at AssocAttrs.get [as getAttribute] (node_modules/src/generators/Generator.js:15:46)
      at AssocAttrs.getAttribute (node_modules/src/generators/AssocAttrs.js:7:23)
      at tryCatch (node_modules/babel-runtime/node_modules/regenerator-runtime/runtime.js:62:40)
      at Generator.invoke [as _invoke] (node_modules/babel-runtime/node_modules/regenerator-runtime/runtime.js:296:22)
      at Generator.prototype.(anonymous function) [as next] (node_modules/babel-runtime/node_modules/regenerator-runtime/runtime.js:114:21)
      at step (node_modules/babel-runtime/helpers/asyncToGenerator.js:17:30)
      at /Users/daniel.pan/Documents/projects/BudgetApp/node_modules/babel-runtime/helpers/asyncToGenerator.js:28:13

这是我拥有的工厂:
import models from '../../models'
import faker from 'faker/locale/en'

export default factory.define('Expense', models.Expense, {
  id: factory.seq('id'),
  value: faker.finance.amount(0, 200),
  note: faker.lorem.sentence(),
  categoryId: factory.assocAttrs('Category', 'id'),
  userId: factory.assocAttrs('User', 'id')
})

我试图将“费用”与“类别”和“用户”联系起来。
我可以只使用“assoc”并且它可以工作,但这适用于我不想要的持久模型。文档说要使用“assocAttrs”来嵌入未持久化的模型,但是我总是遇到类型错误。我不知道如何继续。

最佳答案

这已经很晚了,但是将 categoryId 的代码行更改如下:

categoryId: factory.assocAttrs('Category', 'id'),

至:
categoryId: factory.assocAttrs('Category'),

调用时应该会产生 JSON 输出:
factory.build('Expense').then(x => console.log(x)). 

您会注意到您的 categoryId 属性将包含一个 JSON 对象,该对象将包含初始化为您定义它们的属性。那是 Expense.category = {propA: 'whatever you've defined', probB: 'etc...', categoryId: '123-213-123'}
为确保 Expense.categoryId 属性仅设置为上述 JSON 对象中的 categoryId,您需要将我上面提到的代码行更改为:
categoryId: factory.assocAttrs('Category')().then(y => y.categoryId)

关于sequelize.js - aexmachina/factory-girl(节点)无法将工厂与非持久模型关联起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56351029/

相关文章:

ruby-on-rails - 如何使用 factory_girl 创建同一类但具有不同数据的两个对象?

ruby - FactoryGirl 未在构建中传递参数

javascript - Sequelize 获取重复条目 : 'ER_DUP_ENTRY'

sql - 将同一表中的其他记录数组添加到每条记录

mysql - 使用 Express 中 Sequelize 中的创建方法检查表中存在的 ID

ruby-on-rails - 如何让 FactoryBot 返回正确的 STI 子类?

java - Java 是否存在像 Factory Girl 这样的框架?

sequelize.js - Sequelize 覆盖/更新数据的最佳方式

node.js - 为什么我们需要 Sequelize 'seed' ?

ruby-on-rails - FactoryGirl工厂特征内的序列不使用主序列计数器