KK2491
KK2491

Reputation: 508

Update mongodb subdocuments with different values using mongoose

I am using mongodb in my application as backend database. And trying to update the sub-documents of a document with different values using mongoose.

Below is the sample schema for the document:

'use strict';
 const mongoose = require('mongoose');

 const activitiesSchema = new mongoose.Schema({
   activityId : {
     type: String
   },
   name: {
     type: String,
   },
   points : {
     type : String
   }
 });

 const sampleSchema = new mongoose.Schema(
 {
   userId: {
     type: String,
     require: true,
   },
   userName: {
     type : String,
   },
   activities: {
     type: [activitiesSchema],
   },
   createdTime: {
     type : Date,
     default: Date.now,
   }
 },
);
const Sample = mongoose.model('Samples', sampleSchema, 'Samples');
module.exports = Sample;

I want to update the name to run if the activityId is 001 and, if the activity id is 002 I want the name to be update to walk.

Is this possible to do in single database find and update operation ?

Thank you,
KK

Upvotes: 0

Views: 29

Answers (1)

Charchit Kapoor
Charchit Kapoor

Reputation: 9284

You can use pipelined form of update function, like this:

db.collection.update({},
[
  {
    "$set": {
      "activites": {
        $map: {
          input: "$activites",
          as: "item",
          in: {
            activityId: "$$item.activityId",
            points: "$$item.points",
            name: {
              $switch: {
                branches: [
                  {
                    case: {
                      $eq: [
                        "$$item.activityId",
                        "001"
                      ]
                    },
                    then: "run"
                  },
                  {
                    case: {
                      $eq: [
                        "$$item.activityId",
                        "002"
                      ]
                    },
                    then: "walk"
                  },
                  
                ],
                default: "$$item.name"
              }
            }
          }
        }
      }
    }
  }
],
{
  multi: true
})

Playground link.

Upvotes: 0

Related Questions