MongoDb: What's the best approach to modify a model field from an array of strings to an array of ids that would refer to another model? MongoDb: What's the best approach to modify a model field from an array of strings to an array of ids that would refer to another model? mongoose mongoose

MongoDb: What's the best approach to modify a model field from an array of strings to an array of ids that would refer to another model?


Step 1:

  1. Create a Model for interests,
  • specify your desired fields fir interests schema and set properties for particular fields
  • specify collection name in options as per your requirement
  • create a model and specify your desired name in model
const InterestsSchema = new mongoose.Schema(    { name: { type: String } },    { collection: "interests" });const Interests = mongoose.model("Interests", InterestsSchema);
  1. Instead of removing interests field add new field interest (you can choose desired field), for safe side whenever you feel the current update working properly you can remove it, Update profile schema,
  • update interest field as per your requirement, now newly added field is interest
  interests: {    type: [String]  },  interest: [{    type: Schema.Types.ObjectId,    ref: "interests"  }],

Step 2:

Wherever interests in the app are used in the backend, use interest and populate to fill them.


Step 3: (just execute the query)

Make a collection for interests and store all unique interests string from profile collection, so write a aggregation query to select unique string and store in interests collection, you can execute this query in mongo shell or any editor that you are using after specifying your original profile collection name,

  • $project to show interests field only because we are going to deconstruct it
  • $unwind to deconstruct interests array
  • $group by interests and select unique field, and trim white space from interests string
  • $project to show name field and if you want to then add your desired fields
  • $out will create a new collection interests and write all interests with newly generated _id field
db.getCollection('profile').aggregate([  { $project: { interests: 1 } },  { $unwind: "$interests" },  { $group: { _id: { $trim: { input: "$interests" } } } },  { $project: { _id: 0, name: "$_id" } },  { $out: "interests" }])

Playground

You have example input: