Node.js/Sequelize.js/Express.js - 如何插入多对多关联?(同步/异步?)

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

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

问题描述

我有两个模型(个人、电子邮件)并尝试使用 Sequelize 命令插入到创建的个人电子邮件"表中.当 Sequelize 创建所需的表时,它在尝试向该表添加/获取/设置时返回以下错误:对象 [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."

这让我相信(查看 Promise)我可能误解了如何使用 Node.js 的异步特性.我尝试了同步和异步版本的插入,都返回了上面相同的消息.

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/文档/协会/

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;

/* 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 的方法时,您应该在该承诺上调用 .then() .当它解析时——也就是说,当对象被保存/创建/其他东西时——你的 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 - 如何插入多对多关联?(同步/异步?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Node.js/Sequelize.js/Express.js - 如何插入多对多关联?(同步/异步?)

基础教程推荐