Home > Software design >  How can I update element in array in mongo db node js
How can I update element in array in mongo db node js

Time:11-15

How can I update element in array in one of my objects in database.

I need to update just the page value in certain title. In last viewed I need to have multiple values.

My model looks something like this:

const userSchema = new Schema({
    username: {
        type: String,
        required: true,
        unique: true
    },
    lastViewed: [
        {
            title:{
                type: String,
                required: true
            },
            page:{
                type: Number
            }
        }
    ]
});

This is my node js express app

router.post("/api/update",async(req, res)=>{
    let {token} = req.body;
    let {itemId, page} = req.body;

    if (token == null){
        res.json({status: 'error', error: 'wrong token'});
    }
    
    
    try {
        let userVerification = jwt.verify(token, JWT_SECRET);
        let _id = userVerification.id;
        let item = await Item.findById(itemId);
        await User.updateOne({_id},{
            $set: {
                lastViewed: [
                    {
                        title: item.title,
                        page: page
                    }
                ]
                
            }
        },
        { upsert: true }).catch(err => console.log(err));
        
        res.json({status: 'ok' });
    } catch(err){
        res.json({status: 'error', error: 'wrong token'});
    }
});

What do you think I should do

CodePudding user response:

You point out the element you want to update rather than point to the whole array. The $ operator is used to identify the array element you want to update. Look at the documentation

You can write the update query by

User.update({
  "_id": mongoose.Types.ObjectId(_id),
  "lastViewed.title": "n3"
},
{
  $set: {
    "lastViewed.$.page": 4
  }
})

Check the sample

  • Related