简体   繁体   中英

Dynamoose/DynamoDB update saving empty array as null

I'm using the Node.js package Dynamoose to handle DynamoDB requests in my web application.

Problem is when I try to update the item whenever the JSON object includes an empty array Dynamoose seems to set that to null. Or it could be DynamoDB for all I know.

Below is part of my schema that I'm using for this table.

var NoteSchema = new dynamoose.Schema({
    _id: String,
    details: Array
});

In the code below the variable body is set to {details: []} . I have confirmed this by running console.log(body); .

Note.update({
    _id: searchid
}, body, function(err, note) {
    if (err) {
        console.log(err);
    } else {
        console.log(note);
    }
});

Problem is inside that callback function when running console.log(note); details doesn't even show up at all. So it's null or undefined. In the Amazon Web Services again details doesn't exist at all for that entry.

What is so strange is when creating a new Note, setting details = [] , and saving that, details is an empty array and works perfectly. So to me it seems like a specific problem with updating the record and setting that property to an empty array, since creating a record and setting that property to an empty array works perfectly.

How can I update the record and set details to an empty array?

Figured this out. Submitted this issue to the GitHub repo. Basically the following line ( lib/Model.js about line 396) of code checks to see if the value is an array with length = 0. If so it will delete that JSON key before sending it to AWS.

if(val === null || val === undefined || val === '' || (Array.isArray(val) && val.length === 0)) {

I submitted a pull request using my fork . In that pull request I made the change to allow an optional JSON object parameter of options to be passed into the update function. This is the 3rd parameter of the update function and right before the callback function. If there is a key called emptyarrayallowed and that value is set to true then you that line above will get changed into the following.

if(val === null || val === undefined || val === '') {

For example in my example above changing the update function to the following will work (as long as you are using my fork or the pull request has been approved).

Note.update({_id: searchid}, body, {"emptyarrayallowed": true}, function(err, note) {
    if (err) {
        console.log(err);
    } else {
        console.log(note);
    }
});

Let me know if you have any questions regarding this solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM