我尝试使用.update
方法将值附加到我的某个对象字段,但我当前的代码将字段(organization.members
)中的值替换为字段捕获的新值在post方法中。我在文档中寻找一种附加值的方法(以逗号分隔,但我没有看到任何与向对象属性附加值相关的内容。
这是我的路线:
var express = require('express');
var appRoutes = express.Router();
var passport = require('passport');
var localStrategy = require('passport-local').Strategy;
var models = require('../models/db-index');
appRoutes.route('/settings')
.get(function(req, res){
models.Organization.find({
where: {
organizationId: req.user.organizationId
}, attributes: ['organizationName','admin','members']
}).then(function(organization){
res.render('pages/app/settings.hbs',{
user: req.user,
organization: organization
});
})
})
.post(function(req, res, user){
models.Organization.update({
members: req.body.addMember
},{ where: {
organizationId: req.user.organizationId
}}).then(function(){
console.log("User added to Organization");
res.redirect('/app/settings');
});
});
以下是组织模式:
module.exports = function(sequelize, DataTypes) {
var Organization = sequelize.define('organization', {
organizationId: {
type: DataTypes.INTEGER,
field: 'organization_id',
autoIncrement: true,
primaryKey: true
},
organizationName: {
type: DataTypes.STRING,
field: 'organization_name'
},
admin: DataTypes.STRING,
members: DataTypes.STRING
},{
freezeTableName: true,
classMethods: {
associate: function(db) {
Organization.hasMany(db.User, {foreignKey: 'user_id'});
},
},
});
return Organization;
}
以下是表格:
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="annotation-form">
<h2>Add User</h2>
<form action="/app/settings" method="post">
<input name="addMember" type="text" value="">
<button type="submit">Add User</button>
</form>
<h2><u>Additional Users</u></h2>
{{#each organization}}
<li>{{this.members}}</li>
{{else}}
<p>No additional users</p>
{{/each}}
</div>
</div>
</div>
DB-index.js:
var Sequelize = require('sequelize');
var path = require('path');
var config = require(path.resolve(__dirname, '..', '..','./config/config.js'));
var sequelize = new Sequelize(config.database, config.username, config.password, {
host:'localhost',
port:'3306',
dialect: 'mysql'
});
sequelize.authenticate().then(function(err) {
if (!!err) {
console.log('Unable to connect to the database:', err)
} else {
console.log('Connection has been established successfully.')
}
});
var db = {}
db.Organization = sequelize.import(__dirname + "/organization");
db.User = sequelize.import(__dirname + "/user");
db.Organization.associate(db);
db.sequelize = sequelize;
db.Sequelize = Sequelize;
sequelize.sync();
module.exports = db;
答案 0 :(得分:0)
我有一个类似的问题,就我而言,我正在使用mySQL并使用基础的CONCAT
函数。
我不使用+
连接字符串的原因是您,因为如果字符串包含新行,您可能会收到SQL语法错误
models.Organization.update({
members: Sequelize.fn('CONCAT', Sequelize.col("members"),req.body.addMember)
},{ where: {
organizationId: req.user.organizationId
}}).then(function(){
console.log("User added to Organization");
res.redirect('/app/settings');
});