xxxxxxxxxx
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 () {})
}
})
xxxxxxxxxx
models.User.destroy({where: {userID: '유저ID'}})
.then(result => {
res.json({});
})
.catch(err => {
console.error(err);
});
xxxxxxxxxx
// Delete everyone named "Jane"
await User.destroy({
where: {
firstName: 'Jane',
},
});
sequelize update
xxxxxxxxxx
@Injectable()
export class SequelizeService {
constructor(private sequelize: Sequelize) {}
async transaction(operation: (transaction: Transaction) => Promise<any>, options?: TransactionOptions): Promise<any> {
try {
const transaction = await this.sequelize.transaction({ autocommit: false, options })
try {
const responseTransaction: Record<string, any> = await operation(transaction)
await transaction.commit()
return responseTransaction
} catch (e: any) {
await transaction.rollback()
throw response(e)
}
} catch (e: any) {
response(e)
return null
}
}
async findOneAndUpdate<T = any>(repository: Repository<Model<T, T>>, data: Optional<T, NullishPropertiesOf<T>>, options: FindOptions<T>): Promise<T> {
try {
let repositoryModel: Model<T, T> = await repository.findOne(options)
if (!repositoryModel) return null
repositoryModel = Object.assign(repositoryModel, { data })
return (await repositoryModel.save(options))?.dataValues
} catch (e: any) {
response(e)
return null
}
}
}
xxxxxxxxxx
var Book = db.define(‘books’, {
title: {
type: Sequelize.STRING
},
pages: {
type: Sequelize.INTEGER
}
})
Book.update(
{title: req.body.title},
{where: req.params.bookId}
)