Hi,
I'm trying to add a string to an array of strings. How to do this without fetching the entire array first, then updating it in JS, then overwriting the entire array?
With the "regular" dynamoDB language I would use list_append. How to do such a thing?
const dogSchema = new dynamoose.Schema({
ID: {
type: String,
hashKey: true,
default: uuid,
forceDefault: true,
required: true
},
owners: {
type: Array,
default: []
}
});
export const Dog = dynamoose.model('Dog', dogSchema);
How to add an owner to the owners array?
await Dog.update(
{ ID: 'dogID' }
// And now?
);
@fishcharlie I'm looking for something similar - removing an item from the list. This is how it's done from the terminal - https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.UpdateExpressions.html#Expressions.UpdateExpressions.DELETE
If I understand correctly, to add a new follower to the list of followers for a user I would do:
User.update(
{ username }, // hashKey
{ $ADD: {
followers: 'Jean Valjean',
followersCount: 1,
},
}
);
and this would add Jean Valjean to the set and increment the counter by 1? And then to remove him from that list I would do:
User.update(
{ username }, // hashKey
{ $DELETE: {
followers: 'Jean Valjean',
followersCount: 1,
},
}
);
, removing Jean Valjean from the list and decrementing the counter? Is this correct? Also, suppose I change followers from a set to a map. 'Jean Valjean' becomes the key of a user object. How do I need to update my statements to make it work?
@dolsem I didn't notice that until now. The $ADD update expression can be used to append an item to a DynamoDB list.
@arthurvi try
await Dog.update(
{ ID: 'dogID' },
{ $ADD:
{ owners: [newOwner] }
}
);
As I've mentioned in #398 , I had a similar case and it worked, except that my list type was [String], not Array. Not sure if this will work for Array.
Closing this due to no recent activity. If this is still a problem or you have questions please feel free to comment again and we can try to help further.
@fishcharlie @dolsem
Do you know if it is possible to add an object to an array?
Something like this
await Dog.update(
{ ID: 'dogID' },
{ $ADD:
{ owners:
owner: {
ownerid:'1'
ownername: 'username'
}
}
}
);
With an schema like this
var DogSchema = new Schema({
owners: [ {
owner: {
ownerid: String,
ownername: String
}
}],
@BramSikkens Check out #544