Node.js / Sequelize.js / Express.js - 如何插入多对多关联? (同步/异步?) [英] Node.js / Sequelize.js / Express.js - How to insert into many-to-many association? (sync/async?)

查看:186
本文介绍了Node.js / Sequelize.js / Express.js - 如何插入多对多关联? (同步/异步?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个模型(个人,电子邮件),我正在尝试使用Sequelize命令插入到创建的'Individual_Email'表中。虽然Sequelize正在创建所需的表,但在尝试向该表添加/ get / set时会返回以下错误:Object [object Promise]没有方法'addEmail'。我错过了什么?

I have two models (Individual, Email) and am trying to insert into the created 'Individual_Email' table using the Sequelize commands. While Sequelize is creating the desired table, it returns the following error when trying to add/get/set to/from that table: "Object [object Promise] has no method 'addEmail'". What am I missing?

Sequelize文档说如果模型是User和Project,这将把方法getUsers,setUsers,addUsers添加到Project,getProjects,setProjects和addProject添加到User。

The Sequelize documentation says if the models are User and Project, "This will add methods getUsers, setUsers, addUsers to Project, and getProjects, setProjects and addProject to User."

这让我相信(看看承诺)我可能误解了如何使用Node的异步功能。我已尝试同步和异步版本的插入,两者都返回上面相同的消息。

This leads me to believe (looking at promises) that I'm likely misunderstanding how to use the asynchronous features of Node. I've tried both a synchronous and async version of insertion, both returning the same message above.

Sequelize文档: http://docs.sequelizejs.com/en/latest/docs/associations/

Sequelize Documentation: http://docs.sequelizejs.com/en/latest/docs/associations/

代码:

routes / index.js

var express = require('express');
var router = express.Router();
var models  = require('../models');

/* GET home page. */
router.get('/', function(req, res, next) {
    'use strict';

    var tIndividual, tEmail;
    tIndividual = models.Individual.create({
        name: "Test"
    });
    tEmail = models.Email.create({
        address: "test@gmail.com"
    });
    console.log(tEmail);

    res.render('index', { title: 'Express' });
});

module.exports = router;

OR

/* GET home page. */
router.get('/', function(req, res, next) {
    'use strict';

    var tIndividual, tEmail;    
    tIndividual = models.Individual.create({
        name: "Test"
    }).then(function(){
        tEmail = models.Email.create({
            address: "test@gmail.com"
        }).then(function(){
            tIndividual.addEmail(tEmail).then(function(){
                console.log("Success");
            });
        })
    });

    res.render('index', { title: 'Express' });
});

module.exports = router;

models / index.js

db.Individual.hasMany(db.Email, {
    as: 'Email',
    through: 'Individual_Email'
});
db.Email.hasMany(db.Individual, {
    as: 'Individual',
    through: 'Individual_Email'
});

如何以最佳方式添加到'Individual_Email'表中?我假设我需要同步地等待更新,但我愿意接受任何建议。谢谢!

How can I add to the table 'Individual_Email' in the best way? I'm assuming I need to do it synchronously to wait for the update, but I'm open to any suggestions. Thanks!

推荐答案

当你打电话给 .save() .create()或其他返回Promise的方法,你应该在该promise上调用 .then()。当它结算时 - 也就是说,当对象被保存/创建/被忽略时 - 将调用然后函数,并将接收保存/创建的对象作为一个参数。

When you call .save() or .create() or other methods that return a Promise, you should call .then() on that promise. When it resolves -- that is, when the object gets saved/created/something-elsed -- your then function will be called, and will receive the saved/created object as a parameter.

所以你的第一次尝试可以改写为:

So your first attempt could be rewritten as:

models.Individual.create({
  name: "Test"
}).then(function(createdIndividual) { // note the argument
  models.Email.create({
    address: "test@gmail.com"
  }).then(function(createdEmail) { // note the argument
    createdIndividual.addEmail(createdEmail)
      .then(function(addedEmail) { // note th-- well you get the idea :)
        console.log("Success");
      });
  })
});

上面的代码缺少一些重要的东西,比如 return 承诺更好的链接和错误处理,但这是一个开始。我建议 Bluebird的文档(这是Sequelize使用的Promise库,但还有其他几个)

The above code lacks a few important things, such as returning the promises for better chaining and error handling, but it's a start. I'd recommend Bluebird's documentation on the matter (that's the Promise library that Sequelize uses, but there are several others)

这篇关于Node.js / Sequelize.js / Express.js - 如何插入多对多关联? (同步/异步?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆