Search code examples
node.jsmongodbmongooseschemamongoose-schema

How do I update a [Schema.Types.Mixed]?


I am using Schema.Types.Mixed to store "profiles" and here's my Schema

const userSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      required: true,
      trim: true,
    },
    profiles:{
        type: Schema.Types.Mixed
    }
}

Suppose I have a document with values:

{
    name: "XYZ"
    profiles:{
       "fb" : {
            "name": "XYZ",
            "pic": "source",
            "link": "www.fb.com/xyz"
        },
       "twitter" : {
            "name": "XYZ",
            "pic": "source",
            "link": "www.twitter.com/xyz"
        }  
    }
}

I want to add another field "youtube". How do I write updateOne query such that it upserts this new field in profiles? And how do I update values of these inner fields? Suppose I want to update only "link" fields of fb, how do I do that?


Solution

  • You can use the aggregation pipeline of Mongo

    How do I write updateOne query such that it upserts this new field in profiles?

    db.profiles.aggregate( [
            {
               $addFields: {
                  "profiles.youtube": "add the data here"
               }
            }
       ] )
    

    And how do I update values of these inner fields?

    db.profiles.aggregate( [
            {
               $addFields: {
                  "profiles.twitter.name": "add the data here"
               }
            }
       ] )
    

    This will update the existing field. This pipeline works well if you want to make changes to the whole collection. For more details check this.

    If you want to do that for one document you can do this:

    db.profiles.update({"name": "XYZ" },{$set : {"profiles.youtube":"add data here"}});
    
    // to update existing data
    db.profiles.update({"name": "XYZ" },{$set : {"profiles.twitter":"add data here"}});