0

I'm new to MongoDB and mongoose.

So my model holds many fields, amongst them is an Array of ObjectIDs

var modelSchema = new Schema({
    //...
    inner_array: [Schema.Types.ObjectId],
    //...
});

What I'm trying to achieve with my query is:

Find a model by it's Id,

If the inner array contains a specific value remove it from the array.

If the value is not within the inner_array, push it

var target_id = // document id
var inner_object_id = // value to push

models.MyModel.findOne(
    {_id: target_id},
    function (err, model) {
    // IN THIS SCOPE 'INNER_OBJECT_ID' IS UNDEFINED

    // if model.inner_array contains 'inner_object_id', remove it
    // otherwise, push 'inner_object_id' into model.inner_array

    model.save();
    res.json(model); // return modified document to client
    }
);

I believe this can be written in a single findOneAndUpdate, but I can't figure out the syntax..

Thanks alot!

1 Answer 1

1

I believe you can achieve that using MongooseArray.pull and MongooseArray.addToSet

var target_id = // document id
var inner_object_id = // value to push

models.MyModel.findOne({
  _id: target_id
}, function (err, model) {
  if (model.inner_array.indexOf(inner_object_id) !== -1) {
    model.inner_array.pull(inner_object_id);
  } else {
    model.inner_array.addToSet(inner_object_id);
  }
  model.save();
  res.json(model); // return modified document to client
}
Sign up to request clarification or add additional context in comments.

3 Comments

There was a problem with doing it this way, in the callback function - the 'inner_object_id' variable is undefined. It was defined before
Okay I seem to have passed the variable using .bind()
Glad I could help.

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.