Reputation: 531
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
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
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