fix array field update

This commit is contained in:
Chareice 2021-12-07 15:29:32 +08:00
parent 8765df13ac
commit feea1bef48
2 changed files with 48 additions and 6 deletions

View File

@ -40,6 +40,50 @@ describe('array field operator', function () {
}); });
}); });
test('array field update', async () => {
const Post = db.collection({
name: 'posts',
fields: [
{ type: 'array', name: 'tags' },
],
});
await db.sync({force: true})
await Post.repository.create({})
const p1 = await Post.repository.create({
values: {
tags: ['t1', 't2']
}
})
let result = await Post.repository.findOne({
filter: {
'tags.$match': ['t2', 't1']
}
})
expect(result.get('id')).toEqual(p1.get('id'))
await Post.repository.update({
filterByPk: <number>p1.get('id'),
values: {
tags: ['t3', 't2']
}
})
result = await Post.repository.findOne({
filter: {
'tags.$match': ['t3', 't2']
}
})
expect(result.get('id')).toEqual(p1.get('id'))
});
test('nested array field', async () => { test('nested array field', async () => {
const User = db.collection({ const User = db.collection({
name: 'users', name: 'users',

View File

@ -12,6 +12,7 @@ export class ArrayField extends Field {
sortValue(model) { sortValue(model) {
const oldValue = model.get(this.options.name); const oldValue = model.get(this.options.name);
console.log({oldValue})
if (oldValue) { if (oldValue) {
const newValue = oldValue.sort(); const newValue = oldValue.sort();
model.set(this.options.name, newValue); model.set(this.options.name, newValue);
@ -21,16 +22,13 @@ export class ArrayField extends Field {
bind() { bind() {
super.bind(); super.bind();
if (this.isSqlite()) { this.on('beforeSave', this.sortValue.bind(this));
this.collection.model.addHook('beforeCreate', 'array-field-sort', this.sortValue.bind(this));
}
} }
unbind() { unbind() {
super.unbind(); super.unbind();
if (this.isSqlite()) { this.off('beforeSave', this.sortValue.bind(this));
this.collection.model.removeHook('beforeCreate', 'array-field-sort');
}
} }
} }