1

The problem is that i can't remove an attachment from an object, in mongoose, with the next schema.

var question=mongoose.Schema({
   _id:mongoose.Schema.Types.ObjectId
   answers:[{
     _id:mongoose.Schema.Types.ObjectId
     attachments:[
      _id:mongoose.Schema.Types.ObjectId
     ]
   }]
});

I try to remove an attachment from a document with the next code.

Question.update({ 
  _id: req.params.idQuestion, 
  'answers._id': req.params.idAnswer 
}, { 
  $pull: { 
    'answers.$.attachments':{_id:req.params.idAttachment}
  } 
}, function (err, updated) {
  if(err){
    return res.status(400).send(err);
  }
  else if(!updated.nModified){
    return res.status(400).send('Question hasn\t been updated.');
  }
  
  res.send(200);
  
});

I thought my query weren't correct and tried to do that in mongo shell. It worked perfectly.

db.questions.update({
  _id:ObjectId('xx'),
  'answers._id':ObjectId('yy')
},{
  $pull:{
    'answers.$.attachments':{_id:ObjectId('zz')}
  }
})

Someone can help me with this problem?

1 Answer 1

1

Try this:

var qid=req.params.idQuestion,
    aid=req.params.idAnswer;
//find
Question.find({ 
  _id: qid, 
  'answers._id': aid 
},{
   answers:1
},function(err,question){
   //change
   var answers=question.answers.filter(function(el){
          return el._id!=aid;
       });
   //update
   Question.update({
      _id: qid, 
   },{$set:{
      answers:answers
   }},function(err,updated){
      ...//your callback here
   });
});
Sign up to request clarification or add additional context in comments.

2 Comments

Are you suggesting to remove the attachment without using the mongoose object?
Yes. Find field, modify field, write field to db. Array, string or date... no matter

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.