Ich erstelle eine RESTful-API mit NodeJS, express, express-resource und Sequelize, mit der in einer MySQL-Datenbank gespeicherte Datasets verwaltet werden.
Ich versuche herauszufinden, wie man einen Datensatz mit Sequelize richtig aktualisiert.
Ich erstelle ein Modell:
module.exports = function (sequelize, DataTypes) {
return sequelize.define('Locale', {
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true
},
locale: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
validate: {
len: 2
}
},
visible: {
type: DataTypes.BOOLEAN,
defaultValue: 1
}
})
}
Dann definiere ich in meinem Ressourcencontroller eine Aktualisierungsaktion.
Hier möchte ich in der Lage sein, den Datensatz zu aktualisieren, in dem die ID mit einer req.params
- Variablen übereinstimmt.
Zuerst erstelle ich ein Modell und aktualisiere dann den Datensatz mit der Methode updateAttributes
.
const Sequelize = require('sequelize')
const { dbconfig } = require('../config.js')
// Initialize database connection
const sequelize = new Sequelize(dbconfig.database, dbconfig.username, dbconfig.password)
// Locale model
const Locales = sequelize.import(__dirname + './models/Locale')
// Create schema if necessary
Locales.sync()
/**
* PUT /locale/:id
*/
exports.update = function (req, res) {
if (req.body.name) {
const loc = Locales.build()
loc.updateAttributes({
locale: req.body.name
})
.on('success', id => {
res.json({
success: true
}, 200)
})
.on('failure', error => {
throw new Error(error)
})
}
else
throw new Error('Data not provided')
}
Nun, dies führt nicht zu einer Aktualisierungsabfrage, wie ich es erwarten würde.
Stattdessen wird eine Einfügeabfrage ausgeführt:
INSERT INTO `Locales`(`id`, `locale`, `createdAt`, `updatedAt`, `visible`)
VALUES ('1', 'us', '2011-11-16 05:26:09', '2011-11-16 05:26:15', 1)
Meine Frage lautet also: Wie kann ein Datensatz mit Sequelize ORM ordnungsgemäß aktualisiert werden?
Ich habe Sequelize nicht verwendet, aber nach dem Lesen der Dokumentation ist es offensichtlich, dass Sie ein neues Objekt instanziieren sind, deshalb fügt Sequelize einen neuen Datensatz in die Datenbank ein.
Zuerst müssen Sie nach diesem Datensatz suchen, ihn abrufen und erst danach seine Eigenschaften ändern und pdate it, zum Beispiel:
Project.find({ where: { title: 'aProject' } })
.on('success', function (project) {
// Check if record exists in db
if (project) {
project.update({
title: 'a very different title now'
})
.success(function () {})
}
})
Seit Version 2.0.0 müssen Sie Ihre where -Klausel in eine where
-Eigenschaft einschließen:
Project.update(
{ title: 'a very different title now' },
{ where: { _id: 1 } }
)
.success(result =>
handleResult(result)
)
.error(err =>
handleError(err)
)
In der neuesten Version werden success
und error
nicht mehr verwendet, sondern then
fähige Versprechen.
Der obere Code sieht also folgendermaßen aus:
Project.update(
{ title: 'a very different title now' },
{ where: { _id: 1 } }
)
.then(result =>
handleResult(result)
)
.catch(err =>
handleError(err)
)
try {
const result = await Project.update(
{ title: 'a very different title now' },
{ where: { _id: 1 } }
)
handleResult(result)
} catch (err) {
handleError(err)
}
Seit sequelize v1.7.0 können Sie jetzt eine update () -Methode für das Modell aufrufen. Viel sauberer
Beispielsweise:
Project.update(
// Set Attribute values
{ title:'a very different title now' },
// Where clause / criteria
{ _id : 1 }
).success(function() {
console.log("Project with id =1 updated successfully!");
}).error(function(err) {
console.log("Project update failed !");
//handle error here
});
Und für Leute, die im Dezember 2018 nach einer Antwort suchen, ist dies die richtige Syntax, die Versprechen verwendet:
Project.update(
// Values to update
{
title: 'a very different title now'
},
{ // Clause
where:
{
id: 1
}
}
).then(count => {
console.log('Rows updated ' + count);
});
Ich denke mit UPDATE ... WHERE
wie erklärt hier und hier ist ein schlanker Ansatz
Project.update(
{ title: 'a very different title no' } /* set attributes' value */,
{ where: { _id : 1 }} /* where criteria */
).then(function(affectedRows) {
Project.findAll().then(function(Projects) {
console.log(Projects)
})
Diese Lösung ist veraltet
failure | fail | error () ist veraltet und wird in 2.1 entfernt. Verwenden Sie stattdessen den Versprechungsstil.
also musst du benutzen
Project.update(
// Set Attribute values
{
title: 'a very different title now'
},
// Where clause / criteria
{
_id: 1
}
).then(function() {
console.log("Project with id =1 updated successfully!");
}).catch(function(e) {
console.log("Project update failed !");
})
Sie können auch
.complete()
verwenden
Grüße
Verwenden Sie Async und warten Sie in einem modernen Javascript Es6
const title = "title goes here";
const id = 1;
try{
const result = await Project.update(
{ title },
{ where: { id } }
)
}.catch(err => console.log(err));
sie können das Ergebnis zurückgeben ...
öffentliches statisches Update (Werte: Objekt, Optionen: Objekt): Versprechen>
überprüfen Sie die Dokumentation einmal http://docs.sequelizejs.com/class/lib/model.js~Model.html#static-method-update
Project.update(
// Set Attribute values
{ title:'a very different title now' },
// Where clause / criteria
{ _id : 1 }
).then(function(result) {
//it returns an array as [affectedCount, affectedRows]
})
Sie können die Model.update () -Methode verwenden.
Mit async/wait:
try{
const result = await Project.update(
{ title: "Updated Title" }, //what going to be updated
{ where: { id: 1 }} // where clause
)
} catch (error) {
// error handling
}
Mit .then (). Catch ():
Project.update(
{ title: "Updated Title" }, //what going to be updated
{ where: { id: 1 }} // where clause
)
.then(result => {
// code with result
})
.catch(error => {
// error handling
})
hi um die aufzeichnung zu aktualisieren geht es ganz einfach
result.feild = updatedField
const sequelizeModel = require("../models/sequelizeModel"); const id = req.params.id; sequelizeModel.findAll(id) .then((result)=>{ result.name = updatedName; result.lastname = updatedLastname; result.price = updatedPrice; result.tele = updatedTele; return result.save() }) .then((result)=>{ console.log("the data was Updated"); }) .catch((err)=>{ console.log("Error : ",err) });
Code für V5
const id = req.params.id; const name = req.body.name; const lastname = req.body.lastname; const tele = req.body.tele; const price = req.body.price; StudentWork.update( { name : name, lastname : lastname, tele : tele, price : price }, {returning: true, where: {id: id} } ) .then((result)=>{ console.log("data was Updated"); res.redirect('/'); }) .catch((err)=>{ console.log("Error : ",err) });