How to retrieve value of a variable in class

2019-08-24 02:32发布

问题:

Hello I have a problem to retrieve a value from a method. I'm using sequelize in node.js.

How can get placeTmp['id'] when I do this:

server.js:

var Sequelize = require('sequelize');
var sequelize = new Sequelize(config.database, config.username, config.password);
var Place     = sequelize.import(__dirname + '/model/Place');
console.log(Place.getActualId()); // An ID but I'll retrieve undefined :(

Place.js:

module.exports = function(sequelize, DataTypes) {
var place = sequelize.define('Place', {
    name    : DataTypes.STRING,
    address : DataTypes.STRING,
    city    : DataTypes.STRING,
    zipcode : DataTypes.INTEGER,
    website : DataTypes.STRING,
    start   : DataTypes.DATE,
    end     : DataTypes.DATE,
    type    : DataTypes.STRING,
   actual  : DataTypes.BOOLEAN
},
{
    underscore     : true,
    timestamps     : false,
    freezeTableName: true,
    classMethods: {
        getActualId: function(){
             this.find({where: {actual: 1}}).on('success', function(placeTmp){
             return placeTmp['id'];
     })
   }
}
});

return place;
}

Can you help me ?

Many thanks before

回答1:

Bacause getting an ID is async operation You should do something like this:

    var Sequelize = require('sequelize');
    var sequelize = new Sequelize(config.database, config.username, config.password);
    var Place     = sequelize.import(__dirname + '/model/Place');
    Place.getActualId(function(id){ console.log(id); });


    module.exports = function(sequelize, DataTypes) {
    var place = sequelize.define('Place', {
        name    : DataTypes.STRING,
        address : DataTypes.STRING,
        city    : DataTypes.STRING,
        zipcode : DataTypes.INTEGER,
        website : DataTypes.STRING,
        start   : DataTypes.DATE,
        end     : DataTypes.DATE,
        type    : DataTypes.STRING,
       actual  : DataTypes.BOOLEAN
    },
    {
        underscore     : true,
        timestamps     : false,
        freezeTableName: true,
        classMethods: {
            getActualId: function(callback){
                 this.find({where: {actual: 1}}).on('success', function(placeTmp){
                 callback(placeTmp['id']);
         })
       }
    }
    });

    return place;
    }