gpt4 book ai didi

node.js - Sequelize +数据插入

转载 作者:行者123 更新时间:2023-11-29 13:59:11 26 4
gpt4 key购买 nike

在我的 Node 应用程序中,我使用 sequelize 作为我的 postgresql 数据库的 ORM。以下是我的模型:

用户:

var bcrypt = require('bcrypt'),
crypto = require('crypto');

var authTypes = ['github', 'twitter', 'facebook', 'google'];

var map_attributes = function() {
var obj = new Object(),
ctx = this;
ctx.attributes.forEach(

function(attr) {
obj[attr] = ctx[attr];
});
return obj;
};

var validatePresenceOf = function(value) {
return value && value.length;
};

module.exports = function(sequelize, DataTypes) {
return sequelize.define('user', {
name: {
type: DataTypes.STRING,
validate: {
len: {
args: 1,
msg: "Name cannot be blank"
}
}
},
email: {
type: DataTypes.STRING,
validate: {
len: {
args: 1,
msg: "email cannot be blank"
}
}
},
username: {
type: DataTypes.STRING,
validate: {
len: {
args: 1,
msg: "username cannot be blank"
}
}
},
provider: DataTypes.STRING,
//hashed_password: String,
hashed_password: {
type: DataTypes.STRING,
set: function(v) {
var salt = bcrypt.genSaltSync(10);
var hash = bcrypt.hashSync(v, salt);
this.setDataValue('hashed_password', hash);
}
},
salt: DataTypes.STRING,
/*facebook: {},
twitter: {},
github: {},
google: {}*/
}, {
hooks: {
beforeValidate: function(next) {
if (!this.isNew) return next();
if (!validatePresenceOf(this.password) && authTypes.indexOf(this.provider) === -1) next(new Error('Invalid password'));
else next();
}
}
}, {
instanceMethods: {
authenticate: function(plainText) {
return this.encryptPassword(plainText) === this.hashed_password;
},
makeSalt: function() {
return Math.round((new Date().valueOf() * Math.random())) + '';
},
encryptPassword: function(password) {
if (!password) return '';
return crypto.createHmac('sha1', this.salt).update(password).digest('hex');
}
}
});

}

在这个模型中,我必须将数据插入到我的数据库中。我该如何实现。我找到了这个教程 http://sequelizejs.com/docs/1.7.8/instances但它与我的设计不同,这里我导出的是整个模型。提前致谢。

我试过这个:

index.js:

var Sequelize = require('sequelize');
var util = require('util');
var config = require('config').dbpostgres; // we use node-config to handle environments

// initialize database connection
var sequelize = new Sequelize(
config.dbname,
config.username,
config.password, {
dialect: 'postgres'
});

//var sequelize = new Sequelize('postgres://postgres:postgres@localhost:5432/Geocode', { dialect: 'postgres', protocol: 'postgres' });

// load models
var models = ['user'] //,'sciSphereModel', 'access_token', 'oauth_client', 'request_token', 'article'];

models.forEach(function(model) {
//console.log(model)
var sequelizeModel = sequelize.import(__dirname + '/' + model);
//console.log("seq=" + util.inspect(sequelizeModel));
//sequelizeModel.sync();
/*sequelizeModel.sync().success(function() {
console.log('DB error');
}).error(function(error) {
console.log(error);
})*/

sequelizeModel.sync();

//console.log("sequelizeModel=" + util.inspect(sequelizeModel))
var user = sequelizeModel.build({
name: 'kumar',
email: 'kumar@gmail.com',
username: 'kumar007',
provider: 'local',
hashed_password: 'tyegnaak',
salt: 'uopioann'
})


user.save().complete(function(err) {
console.log("Inside user save");
if ( !! err) {
console.log('The instance has not been saved:', err)
}
else {
console.log('We have a persisted instance now')
}
})
module.exports[model] = sequelizeModel; //Implement sync
});
// export connection
//sequelize.sync();
module.exports.sequelize = sequelize;
app.set('sequelize', sequelize);

我做的对吗?这是实现目标的方法吗?

最佳答案

不会是 sequelize.sync(); 而不是 sequelizeModel.sync(); 因为你想同步任何模型更改与数据库。如果表格与您的模型不匹配,您还可以强制同步。

sequelize.sync({ force: true });//用于创建前删除

我从未在模型上尝试过同步,只是 create()save()find()updateAttributes ()

关于node.js - Sequelize +数据插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24603361/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com