Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

106
Views
Convert String fields to ObjectID fields in MongoDB using Mongoose

I have a MongoDB database with two schemas - users and posts. It used to look like this:

username: {type: String},
following: {type: [String], ref: 'users'}

user_id: {type: String, ref: 'users'}
comment: {type: String}

But now I've decided to change reference fields' types from String to ObjectId so now I have:

username: {type: String},
following: {type: [Schema.Types.ObjectId], ref: 'users'}

user_id: {type: Schema.Types.ObjectId, ref: 'users'}
comment: {type: String}

But the old data in the database is still stored as Strings. How can I migrate that data properly?

I use Mongoose to query the database from my code.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

You should use model.find({}) to fetch all the post documents and after that loop through each document and update each document

doc.user_id = mongoose.Types.ObjectId(doc.user_id); 
doc.save();
over 4 years ago · Santiago Trujillo Report

0

You can use model.find({}) to get all documents and loop through the docs and update it.


const media = await Media.find({});
            media.forEach(async (item) => {
            const update = await Media.findOneAndUpdate(
                    { _id: item._id },
                    { user: mongoose.Types.ObjectId(item.user) },
                    { upsert: true }
                );
            });```
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!