2

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.

6
  • Are the strings valid ObjectId hex values? Commented Jan 28, 2017 at 15:33
  • @chridam Yes, they are. Commented Jan 28, 2017 at 15:35
  • i think you shoud use model.find({}) all the post documents and after that loop through each docment and doc. user_id = mongoose.Types.ObjectId(doc.user_id); and do doc.save on each document Commented Jan 28, 2017 at 15:46
  • Why I typically do is convert my old data with mongo shell script Commented Jan 28, 2017 at 16:41
  • @AsifSaeed Thanks, this is what I eventually did. Commented Jan 28, 2017 at 17:26

2 Answers 2

3

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();
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.