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
    Nov 12 at 15:50















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
    Nov 12 at 15:50













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 Nov 12 at 16:17

























asked Nov 12 at 15:23









user545871

375




375








  • 1




    You need to use $pull to remove an element from the array
    – Anthony Winzlet
    Nov 12 at 15:50














  • 1




    You need to use $pull to remove an element from the array
    – Anthony Winzlet
    Nov 12 at 15:50








1




1




You need to use $pull to remove an element from the array
– Anthony Winzlet
Nov 12 at 15:50




You need to use $pull to remove an element from the array
– Anthony Winzlet
Nov 12 at 15:50












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















      Required, but never shown

























      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 Nov 12 at 15:50









          Jack

          2,4731525




          2,4731525
























              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 Nov 12 at 16:28









                  Babak

                  20119




                  20119






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.





                      Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                      Please pay close attention to the following guidance:


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      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















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      How to pass form data using jquery Ajax to insert data in database?

                      National Museum of Racing and Hall of Fame

                      Guess what letter conforming each word