Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

104
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda