CorrieSparrow
CorrieSparrow

Reputation: 531

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.

Upvotes: 2

Views: 7840

Answers (2)

Rohail Butt
Rohail Butt

Reputation: 461

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 }
                );
            });```

Upvotes: 0

Asif Saeed
Asif Saeed

Reputation: 2045

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();

Upvotes: 3

Related Questions