简体   繁体   中英

How to delete particular subdocument in mongoose

Hi I'm new to MongoDB and programming. I'm trying to delete particular subdocument in particular parent document and I'm using Mongoose and Node.js. Here is my Schema model (user.js file):

var userStuff = mongoose.Schema({
  itemName: String,
  itemDesc: String
});

var userSchema = mongoose.Schema({
  googleEmail: String,
  googleName: String,
  stuff: [userStuff]
});

exports.user = mongoose.model('User', userSchema);
exports.userStuff = mongoose.model('UserStuff', userStuff);

Here is how I try to delete:

  var User = require("../../models/user.js");
  ...
  var userId = req.session.passport.user;
  var deleteItemId = req.params.id;
  User.user.findOne({_id: userId}, function(err, user){
    if(err){
        console.log(err);
      }else {
        User.userStuff.remove({ _id: deleteItemId}, function(err, data){
          if(err){
            console.log(err);
          }else{
            user.save(function(err){
              if(err){
              console.log(err);
              } else {
              res.status(200).send();
              }
            });
          }
        });

    }
  });

Can you show how I can delete particular item for particular user?

To delete particular item for particular user, you can use the $pull operator to remove the subdocument with an atomic update:

User.user.update(
    { "_id": req.session.passport.user },
    { "$pull": { "stuff": { "_id": req.params.id } } },
    function(err, numAffected) { 
        if(err){
            console.log(err);
        } else {
            res.status(200).send();
        }
    }
);

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