Search code examples
node.jsmongodbmongoosemongodb-querymongoose-schema

How can I Change value inside array of schemes inside schema with mongoose or mongodb query.?


i have the following schema type: Paitnet:

var PaitentSchema = new mongoose.Schema({
    username: String,
    password: String,
    name: String,
    protocol: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Protocol'
    },

    treatmentTypes: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'TreatmentType'
    }],

    accesses: [AccessSchema],
    reports: [ReportSchema],
}, { collection: ' Paitents' });

and the AccessSchema:

var AccessSchema = new mongoose.Schema({
    stageBool: Boolean,
    exerciseBool: [{ type: Boolean }]

});

and what I'm trying to do is to update the exerciseBool array for example change one of the values in the array from 'false' to 'true'. I have tried this code and its work for me but the Problem is that I get the index from the client so I need to embed the indexes in dynamically way (not always 0 and 1)

here is what I did(not dynamically ):

  const paitent = await Paitent.updateOne({ username: req.params.username }, 
        { $set: { "accesses.0.exerciseBool.1": true } });

I want to do something like this but in dynamically indexes way. please someone can help me? thanks.


Solution

  • As you said, indexes are known but values may change.

    you can use the following to create your query.

    const accessesIndex = 0;
    const exerciseBoolIndex = 1;
    
    const update = { $set: { [`accesses.${accessesIndex}.exerciseBool.${exerciseBoolIndex}`]: true } };
    
    console.log(update);
    
    //const paitent = await Paitent.updateOne({ username: req.params.username }, update); // run your update query like this

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals


    Update

    Check the index exists or not then only update the record.

    add into your query "accesses.0.exerciseBool.1": { $exists: true } to make sure the accesses.0.exerciseBool.1 exists in the record.

    const accessesIndex = 0;
    const exerciseBoolIndex = 1;
    
    const username = 'abc';
    
    const key = `accesses.${accessesIndex}.exerciseBool.${exerciseBoolIndex}`;
    
    const query =  { username, [key]: { "$exists": true } };
    
    console.log('query:', query);
    
    const update = { $set: { [key]: true } };
    
    console.log('update:', update);

    Update Working demo - https://mongoplayground.net/p/GNOuZr3wqqw

    No update demo - https://mongoplayground.net/p/nsTC8s-ruyo