System Information
- strapi": "^3.2.3
- Mac OS 10.9
- MongoDB Atlas
- Node v12.14.1
- NPM 6.14.5
- Yarn 1.22.4
I’m wondering if anyone has encountered the issue I’m having with attempting to programmatically delete an element from a relation field. The relation field is an array. I can easily add element objects to the relation, but when I attempt to delete an element I get a Javascript Strict Mode error:
- TypeError – Can’t delete non-configurable array element (message returned by FireFox)
- TypeError – Cannot delete property ‘1’ of [object Array] (message returned by Chrome)
Both of the error messages refer to the same Strict Mode Error relating to not allowing the shortening of a non-configurable array.
Clearly, there is a way to do this since I can delete a relation element from the Strapi UI panel. My code follows:
// get index of object
let updateValue = cartItems
.map(function (item) {
return item.id;
})
.indexOf(currentUser);
console.log("updateValue " + updateValue); // this returns 1 as the index position of the target element in a two-item array.
// remove object
cartItems.splice(updateValue, 1);
The code above finds the index of the target element, but the Array.splice() method fails, reporting the non-configurable array error.
Thoughts?
Thanks… Jim
Excuse my ignorance as I’m much more devops focused and still learning the finer code skills in javascript. Would it not be easier to just use a .map and a delete path.in.the.object
to iterate over the array of objects and delete the key(s) similar to our guide in the docs?
@Dmehaffy, thanks for your feedback. I followed the Strapi controller docs and after playing around with many different iterations of the code below, I’m still stuck.
`const { parseMultipartData, sanitizeEntity } = require(“strapi-utils”);
module.exports = {
async update(ctx) {
const { id } = ctx.params;
const { user } = ctx.state;
let entity;
if (ctx.is("multipart")) {
const { data, files } = parseMultipartData(ctx);
entity = await strapi.services.product.update({ id }, data, {
files,
});
} else {
// return id; = 5fa47483e87eddaad31766c6 from const { id } = ctx.params;
entity = await strapi.services.product
.update({ id }, ctx.request.body, {
$pull: {
userCarts: {
_id: "5f832758ef13ed4f801c8937",
},
},
})
}
return sanitizeEntity(entity, { model: strapi.models.product });
}
}`
My product is returned but the userCarts item is not deleted.
I also tested code that was suggested on Strapi’s Slack channel by replacing:
entity = await strapi.services.product.update(
with
entity = await strapi.query("product").model.updateOne(
No joy on that code change, either.
Mongoose $pull seems to have a history of issues related to not working. From what I’ve read, it essentially depends on “_id”, though some have had success using other fields as target values. “_id” is my target value for userCarts.
Does Strapi have its own implementation for $pull?
Thoughts?
Thanks… Jim