How to find and delete a particular object in an Array of Object in Mongoose











up vote
2
down vote

favorite












I have this following Mongoose User Schema:



postCreated:{
type: Array,
default:
}


which contains an Array of Object of Posts belong to that user. I plan to do the following: When I delete a particular post, I pass the id of that post and the username of the user that created to the back-end and hope that it would remove the post from both Post schema and postCreated of a user that it belongs to



server.del('/posts',(req,res,next)=>{
const {id,username} = req.body;
User.findOne({username}).then(user => {
console.log(user.postCreated)
user.postCreated.filter(post => {
post._id !== id;
});
console.log(user.postCreated)
});
Posts.findOneAndRemove({_id: id}).then((post) => {
if(!post){
return next(new errors.NotFoundError('Post not found'));
}
res.send(post);
})
.catch((e) => {
return next(new errors.BadRequestError(e.message));
});
});


However, the post only got removed from the Post Model, and not from postCreated of User Model, meaning that the user.postCreated.filter did not work.



I have tried the following, thanks to Jack, but seems like it did not solve the issue:



    User.update(
{ username },
{ $pull: { postCreated: {_id: id} } },
{ multi: true }
);


Is there any way that I could fix this?



I would really appreciate any help.










share|improve this question




















  • 1




    You need to use $pull to remove an element from the array
    – Anthony Winzlet
    yesterday















up vote
2
down vote

favorite












I have this following Mongoose User Schema:



postCreated:{
type: Array,
default:
}


which contains an Array of Object of Posts belong to that user. I plan to do the following: When I delete a particular post, I pass the id of that post and the username of the user that created to the back-end and hope that it would remove the post from both Post schema and postCreated of a user that it belongs to



server.del('/posts',(req,res,next)=>{
const {id,username} = req.body;
User.findOne({username}).then(user => {
console.log(user.postCreated)
user.postCreated.filter(post => {
post._id !== id;
});
console.log(user.postCreated)
});
Posts.findOneAndRemove({_id: id}).then((post) => {
if(!post){
return next(new errors.NotFoundError('Post not found'));
}
res.send(post);
})
.catch((e) => {
return next(new errors.BadRequestError(e.message));
});
});


However, the post only got removed from the Post Model, and not from postCreated of User Model, meaning that the user.postCreated.filter did not work.



I have tried the following, thanks to Jack, but seems like it did not solve the issue:



    User.update(
{ username },
{ $pull: { postCreated: {_id: id} } },
{ multi: true }
);


Is there any way that I could fix this?



I would really appreciate any help.










share|improve this question




















  • 1




    You need to use $pull to remove an element from the array
    – Anthony Winzlet
    yesterday













up vote
2
down vote

favorite









up vote
2
down vote

favorite











I have this following Mongoose User Schema:



postCreated:{
type: Array,
default:
}


which contains an Array of Object of Posts belong to that user. I plan to do the following: When I delete a particular post, I pass the id of that post and the username of the user that created to the back-end and hope that it would remove the post from both Post schema and postCreated of a user that it belongs to



server.del('/posts',(req,res,next)=>{
const {id,username} = req.body;
User.findOne({username}).then(user => {
console.log(user.postCreated)
user.postCreated.filter(post => {
post._id !== id;
});
console.log(user.postCreated)
});
Posts.findOneAndRemove({_id: id}).then((post) => {
if(!post){
return next(new errors.NotFoundError('Post not found'));
}
res.send(post);
})
.catch((e) => {
return next(new errors.BadRequestError(e.message));
});
});


However, the post only got removed from the Post Model, and not from postCreated of User Model, meaning that the user.postCreated.filter did not work.



I have tried the following, thanks to Jack, but seems like it did not solve the issue:



    User.update(
{ username },
{ $pull: { postCreated: {_id: id} } },
{ multi: true }
);


Is there any way that I could fix this?



I would really appreciate any help.










share|improve this question















I have this following Mongoose User Schema:



postCreated:{
type: Array,
default:
}


which contains an Array of Object of Posts belong to that user. I plan to do the following: When I delete a particular post, I pass the id of that post and the username of the user that created to the back-end and hope that it would remove the post from both Post schema and postCreated of a user that it belongs to



server.del('/posts',(req,res,next)=>{
const {id,username} = req.body;
User.findOne({username}).then(user => {
console.log(user.postCreated)
user.postCreated.filter(post => {
post._id !== id;
});
console.log(user.postCreated)
});
Posts.findOneAndRemove({_id: id}).then((post) => {
if(!post){
return next(new errors.NotFoundError('Post not found'));
}
res.send(post);
})
.catch((e) => {
return next(new errors.BadRequestError(e.message));
});
});


However, the post only got removed from the Post Model, and not from postCreated of User Model, meaning that the user.postCreated.filter did not work.



I have tried the following, thanks to Jack, but seems like it did not solve the issue:



    User.update(
{ username },
{ $pull: { postCreated: {_id: id} } },
{ multi: true }
);


Is there any way that I could fix this?



I would really appreciate any help.







node.js mongodb mongoose






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited yesterday

























asked yesterday









user545871

254




254








  • 1




    You need to use $pull to remove an element from the array
    – Anthony Winzlet
    yesterday














  • 1




    You need to use $pull to remove an element from the array
    – Anthony Winzlet
    yesterday








1




1




You need to use $pull to remove an element from the array
– Anthony Winzlet
yesterday




You need to use $pull to remove an element from the array
– Anthony Winzlet
yesterday












2 Answers
2






active

oldest

votes

















up vote
1
down vote













You can use mongoose $pull



Use: https://docs.mongodb.com/manual/reference/operator/update/pull/



User.update(
{ username },
{ $pull: { postCreated: id } },
{ multi: true }
);


This should solve your query.






share|improve this answer




























    up vote
    1
    down vote













    If you want to do it the way you were doing you need to store back your postCreated array into it self and then save the user:



    User.findOne({username}).then(user => {
    console.log(user.postCreated)
    user.postCreated = user.postCreated.filter(post => {
    post._id !== id;
    });
    console.log(user.postCreated);
    user.save();
    });


    But the best way is findOneAndUpdate if you need the user object later on.






    share|improve this answer





















      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














       

      draft saved


      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53265209%2fhow-to-find-and-delete-a-particular-object-in-an-array-of-object-in-mongoose%23new-answer', 'question_page');
      }
      );

      Post as a guest
































      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      1
      down vote













      You can use mongoose $pull



      Use: https://docs.mongodb.com/manual/reference/operator/update/pull/



      User.update(
      { username },
      { $pull: { postCreated: id } },
      { multi: true }
      );


      This should solve your query.






      share|improve this answer

























        up vote
        1
        down vote













        You can use mongoose $pull



        Use: https://docs.mongodb.com/manual/reference/operator/update/pull/



        User.update(
        { username },
        { $pull: { postCreated: id } },
        { multi: true }
        );


        This should solve your query.






        share|improve this answer























          up vote
          1
          down vote










          up vote
          1
          down vote









          You can use mongoose $pull



          Use: https://docs.mongodb.com/manual/reference/operator/update/pull/



          User.update(
          { username },
          { $pull: { postCreated: id } },
          { multi: true }
          );


          This should solve your query.






          share|improve this answer












          You can use mongoose $pull



          Use: https://docs.mongodb.com/manual/reference/operator/update/pull/



          User.update(
          { username },
          { $pull: { postCreated: id } },
          { multi: true }
          );


          This should solve your query.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered yesterday









          Jack

          2,3801525




          2,3801525
























              up vote
              1
              down vote













              If you want to do it the way you were doing you need to store back your postCreated array into it self and then save the user:



              User.findOne({username}).then(user => {
              console.log(user.postCreated)
              user.postCreated = user.postCreated.filter(post => {
              post._id !== id;
              });
              console.log(user.postCreated);
              user.save();
              });


              But the best way is findOneAndUpdate if you need the user object later on.






              share|improve this answer

























                up vote
                1
                down vote













                If you want to do it the way you were doing you need to store back your postCreated array into it self and then save the user:



                User.findOne({username}).then(user => {
                console.log(user.postCreated)
                user.postCreated = user.postCreated.filter(post => {
                post._id !== id;
                });
                console.log(user.postCreated);
                user.save();
                });


                But the best way is findOneAndUpdate if you need the user object later on.






                share|improve this answer























                  up vote
                  1
                  down vote










                  up vote
                  1
                  down vote









                  If you want to do it the way you were doing you need to store back your postCreated array into it self and then save the user:



                  User.findOne({username}).then(user => {
                  console.log(user.postCreated)
                  user.postCreated = user.postCreated.filter(post => {
                  post._id !== id;
                  });
                  console.log(user.postCreated);
                  user.save();
                  });


                  But the best way is findOneAndUpdate if you need the user object later on.






                  share|improve this answer












                  If you want to do it the way you were doing you need to store back your postCreated array into it self and then save the user:



                  User.findOne({username}).then(user => {
                  console.log(user.postCreated)
                  user.postCreated = user.postCreated.filter(post => {
                  post._id !== id;
                  });
                  console.log(user.postCreated);
                  user.save();
                  });


                  But the best way is findOneAndUpdate if you need the user object later on.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered yesterday









                  Babak

                  1668




                  1668






























                       

                      draft saved


                      draft discarded



















































                       


                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53265209%2fhow-to-find-and-delete-a-particular-object-in-an-array-of-object-in-mongoose%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest




















































































                      Popular posts from this blog

                      Biblatex bibliography style without URLs when DOI exists (in Overleaf with Zotero bibliography)

                      ComboBox Display Member on multiple fields

                      Is it possible to collect Nectar points via Trainline?