为什么续集对象在这种情况下没有setOwner方法?

时间:2018-05-01 02:19:55

标签: javascript node.js sequelize.js

我是续集器的新手,无法弄清楚为什么这会导致setOwner的错误不是一个功能。我想也许它是在错误的上下文中执行的,但我注销了它所调用的对象,它看起来像是大型的sequelize对象......这里是我的代码和错误,如果有人可以指出我的正确的方向。

种子文件:

const { Vegetable, Gardener, Plot, db }= require('./models');

const vegetables = [{
      name: 'Carrot',
      color: 'Orange',
      planted_on: new Date()
    },
    {
      name: 'Cucumber',
      color: 'Green',
      planted_on: new Date()
    },
    {
      name: 'Broccoli',
      color: 'Green',
      planted_on: new Date()
    },
    {
      name: 'Eggplant',
      color: 'Purple',
      planted_on: new Date()
}];
const gardeners = [{
      name: 'Bill',
      age: 35
    },
    {
      name: 'Suzan',
      age: 45
    },
    {
      name: 'Teresa',
      age: 55
    },
    {
      name: 'Andrew',
      age: 65
}];
const plots = [{
      size: 6,
      shaded: true
    },
    {
      size: 6,
      shaded: false
    },
    {
      size: 6,
      shaded: 0
    },
    {
      size: 6,
      shaded: 1
}];

db.sync({force: true})
  .then( _ => Promise.all(vegetables.map(vegetable => Vegetable.create(vegetable))))
  .then( _ => Promise.all(gardeners.map(gard => Gardener.create(gard))))
  .then( _ => Promise.all(plots.map(pl => Plot.create(pl))))
  .then( _ => Promise.all([Vegetable.findAll(), Gardener.findAll(), Plot.findAll()]))
  .then( data => {
      let calls = [];
      for(let i = 0; i < data[0].length; i++){
          calls.push(Gardener.findById(data[0][i].dataValues.id).then(gdnr => {
              console.log(gdnr);
              //Can't figure out why this isn't a function here
              return gdnr.setOwner(data[0][i].dataValues.id);
          }));
          //Gardener.findById(data[0][i].dataValues.id).then()//set gardner to a veggie foreign
          //Plot.findById(data[0][i].dataValues.id)//set plot a gardner foreign
      }
      return Promise.all(calls);
  })
  .catch(err => {
    console.log(err)
  })
  .finally(() => {
    db.close();
  })

MODEL:

const Sequelize = require('sequelize');

const db = new Sequelize('postgres://localhost:5432/plantr', {logging: false});

const Gardener = db.define('gardeners', {
  name: Sequelize.STRING,
  age: Sequelize.INTEGER
});

const Plot = db.define('plots', {
  size: Sequelize.INTEGER,
  shaded: Sequelize.BOOLEAN
});

const Vegetable = db.define('vegetables', {
  name: Sequelize.STRING,
  color: Sequelize.STRING,
  planted_on: Sequelize.DATE
});

Plot.belongsTo(Gardener);
Gardener.hasOne(Plot);

Vegetable.belongsToMany(Gardener, {through: 'vegetable_plot'});
Gardener.belongsToMany(Vegetable, {through: 'vegetable_plot'});

Gardener.belongsTo(Vegetable, {as: 'favorite_vegetable'});

module.exports = {
    Gardener, Plot, Vegetable, db
}

错误日志:

TypeError: gdnr.setOwner is not a function
    at Gardener.findById.then.gdnr (/Users/amc/Documents/fullstack/plantr/seed.js:71:23)
    at tryCatcher (/Users/amc/Documents/fullstack/plantr/node_modules/bluebird/js/release/util.js:16:23)
    at Promise._settlePromiseFromHandler (/Users/amc/Documents/fullstack/plantr/node_modules/bluebird/js/release/promise.js:512:31)
    at Promise._settlePromise (/Users/amc/Documents/fullstack/plantr/node_modules/bluebird/js/release/promise.js:569:18)
    at Promise._settlePromise0 (/Users/amc/Documents/fullstack/plantr/node_modules/bluebird/js/release/promise.js:614:10)
    at Promise._settlePromises (/Users/amc/Documents/fullstack/plantr/node_modules/bluebird/js/release/promise.js:693:18)
    at Async._drainQueue (/Users/amc/Documents/fullstack/plantr/node_modules/bluebird/js/release/async.js:133:16)
    at Async._drainQueues (/Users/amc/Documents/fullstack/plantr/node_modules/bluebird/js/release/async.js:143:10)
    at Immediate.Async.drainQueues [as _onImmediate] (/Users/amc/Documents/fullstack/plantr/node_modules/bluebird/js/release/async.js:17:14)
    at runCallback (timers.js:763:18)
    at tryOnImmediate (timers.js:734:5)
    at processImmediate (timers.js:716:5)

OBJCT在错误之前记录:

gardeners { 
dataValues: 
   { id: 2,
     name: 'Suzan',
     age: 45,
     createdAt: 2018-05-01T02:11:53.993Z,
     updatedAt: 2018-05-01T02:11:53.993Z,
     favoriteVegetableId: null },
  _previousDataValues: 
   { id: 2,
     name: 'Suzan',
     age: 45,
     createdAt: 2018-05-01T02:11:53.993Z,
     updatedAt: 2018-05-01T02:11:53.993Z,
     favoriteVegetableId: null },
  _changed: {},
  _modelOptions: 
   { timestamps: true,
     validate: {},
     freezeTableName: false,
     underscored: false,
     underscoredAll: false,
     paranoid: false,
     rejectOnEmpty: false,
     whereCollection: { id: 2 },
     schema: null,
     schemaDelimiter: '',
     defaultScope: {},
     scopes: [],
     indexes: [],
     name: { plural: 'gardeners', singular: 'gardener' },
     omitNull: false,
     sequelize: 
      Sequelize {
        options: [Object],
        config: [Object],
        dialect: [PostgresDialect],
        queryInterface: [QueryInterface],
        models: [Object],
        modelManager: [ModelManager],
        connectionManager: [ConnectionManager],
        importCache: {},
        test: [Object] },
     hooks: {},
     uniqueKeys: {} },
  _options: 
   { isNewRecord: false,
     _schema: null,
     _schemaDelimiter: '',
     raw: true,
     attributes: 
      [ 'id',
        'name',
        'age',
        'createdAt',
        'updatedAt',
        'favoriteVegetableId' ] },
  __eagerlyLoadedAssociations: [],
  isNewRecord: false }

还有一个未定义的记录功能,但我认为这不会有帮助

1 个答案:

答案 0 :(得分:0)

获取所有者不是园丁的续集对象上可用的方法,因为它与另一个表的关系不是由所有者,它的蔬菜表的外键是favorite_vegetable;所以方法是setFavorite_vegetable(vegetable id或vegetableObject)。