0

i am trying to update a value in the object of my embedded schema(comments schema) whose value i had previously stored 0 by default. i have tried all the ways to update but none of the stackoverflow answer worked. my code is

var checkedBox = req.body.checkbox;       
User.updateOne({_id: foundUser._id},{$set :{comments:{_id :checkedBox,cpermission:1,}}},function(err,updatec){
          if(err){
            console.log(err);
          }
          else{
            console.log("successfull");
      console.log(updatec);

          }
        });

i had comment schema nested in user schema,here foundUser._id is the particular users id,and checkedBox id is the embedded objects particular id. previously my cpermission was 0,set by default,but now i want to update it to 1. although this is updating my schema,but deleting the previous images and comments in the schema aswell. where am i going wrong?

here is my schema

const commentSchema = new mongoose.Schema({
  comment: String,
  imagename: String,
    cpermission:{type:Number,default:0},
});

const Comment = new mongoose.model("Comment", commentSchema);

const userSchema = new mongoose.Schema({
  firstname: String,
  lastname: String,
  email: String,
  password: String,
  comments: [commentSchema],
  upermission:{type:Number,default:0},
});

userSchema.plugin(passportLocalMongoose);

const User = new mongoose.model("User", userSchema);
6
  • You want commets cpermission to be 1, in all the comments where it was 0 before, is that right? Commented May 22, 2020 at 9:45
  • yeah,but not for all,but only for the id's i pass through checkedBox Commented May 22, 2020 at 9:49
  • checkedBox is an array of ids? Commented May 22, 2020 at 9:52
  • yes,its an array of id's Commented May 22, 2020 at 10:16
  • I have submitted an answer please check, if it doesn't solve your problem, please tell me in comment Commented May 22, 2020 at 10:21

3 Answers 3

1

First, you need to convert checkbox in the array, as it will be a string if you select a single element

Then wrap it with mongoose.Types.ObjectId as a precaution

Then you can use arrayFilters to update multiple matching array elements

var checkedBox = req.body.checkbox;
if (!Array.isArray(checkedBox)) {
   checkedBox = [checkedBox]
}

checkedBox = checkedBox.map(id => mongoose.Types.ObjectId(id))

User.updateOne(
    { _id: foundUser._id }, // filter part
    { $set: { 'comments.$[comment].cpermission': 1 } }, // update part
    { arrayFilters: [{ 'comment._id': {$in: checkedBox }}] }, // options part
    function (err, updatec) {
        if (err) {
            console.log(err);
        }
        else {
            console.log("successfull");
            console.log(updatec);

        }
    });
Sign up to request clarification or add additional context in comments.

2 Comments

yes this is what i was looking for. working fine,thanks alot.
Happy to help :)
0

your comment is the array of documents. if you want to update an element of an array must be select it. for that must be added another condition to the first section of updateOne then in seconde section use $ for update selected element of the array.

User.updateOne(
        {_id: foundUser._id, 'comments._id': checkedBox},
        {
            $set: {'comments.$.cpermission': 1}
        }
        , function (err, updatec) {
            if (err) {
                console.log(err)
            }
            else {
                console.log('successfull')
                console.log(updatec)
            }
        })

for more information, you can read this document form MongoDB official website. Array Update Operators

3 Comments

it's not your answer? why do you remove the answer flag?
its only updating the first passed element,not all elements of the array whose id is passes through checkedBox
that's true. but your condition is on the _id field and that is unique in the comments list then its find one comment.
0
  var checkedBox = req.body.checkbox;

  User.updateOne(
  { _id: foundUser._id, "comment._id": checkedBox },
  { $set: { "comment.$.cpermission": 1 } },
  function (err, update) {
  if (err) {
    console.log(err);
  } else {
    console.log("successfull");
    console.log(update);
  }
 }
 );

3 Comments

this will update the first element in the array, not a specific element with some condition ... the positional $ operator acts as a placeholder for the first element that matches the query document, you can check the docs for all the array update operators here docs.mongodb.com/manual/reference/operator/update-array
@MohammedYousry in documentation tell Acts as a placeholder to update the first element that matches the query condition. if you add a correct condition that's work true.
if we have some comments array with this order in db [commentI1, comment2, comment3], and you want to update comment3, and you passed { _id: foundUser._id, "comment._id": comment3 } as a filter, you will get the document with the whole array, then update the first element in the array which is comment1, not comment3

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.