Trying to delete an object from an array list, after being .splice()
then save it to DB. Though it's splicing the correct index
but not saving it correctly, if I splice
index 0
, its actually deleting index 1
in the DB, probably because of the object has been spliced first therefore it's saving the wrong object.
var user =
{
"request": [
{ "name": "test1", "url": "test1.com" },
{ "name": "test2", "url": "test2.com" }
]
}
Splicing it and saving
let xd = user.requests.indexOf(acceptOrdeny);
user.requests.splice(xd, 1);
user.save(callback);
full code logic --
User.findOne({ _id: currUser._id }, function (err, user) {
if (err) throw err;
/* acceptOrdeny is the req.body object
checking if the key accepted==true then push acceptOrdeny object to friends[], splice from request[] then save to DB
*/
if (acceptOrdeny.accepted == true) {
user.friends.push(acceptOrdeny);
let indexReq = user.requests.indexOf(acceptOrdeny);
user.requests.splice(indexReq, 1);
user.save(callback);
console.log('accepted', indexReq)
}
/*
checking if the key accepted==false remove from requests[], then save current array[] list
*/
else {
let xd = user.requests.indexOf(acceptOrdeny);
user.requests.splice(xd, 1);
user.save(callback);
}
});
I have tested splice
the object manual like, this is fine but splicing them dynamically using indexOf
is not quite right.
user.requests.splice(0, 1); // delete first obj in the array 'test1'
user.requests.splice(1, 1); // delete 2nd obj in the array 'test2'
Is there a better way of deleting the object in the obj[] list then save it back to the DB?
via MrNew
No comments:
Post a Comment