javorosas
javorosas

Reputation: 769

Mongoose can't find any elements after changing property type

I originally have these two schemas:

var UserSchema = new Schema({
  first: String,
  last: String
});

var SaleSchema = new Schema({
  createdAt: Date,
  registeredBy: { type: Schema.ObjectId, ref: 'User' }
});

But I want to edit my SaleSchema to save the user name instead of the ID, so I changed it for:

var SaleSchema = new Schema({
  createdAt: Date,
  registeredBy: String
});

Next, I wanted to edit all the Sales documents and replace the user IDs on registeredBy for the user's full name, but I can't seem to be able to perform a find query for the old ID's.

Long story short, this query returns no matches on mongoose, but it works perfectly using the mongo console:

Mongoose

Sale.find({ registeredBy: '57ea0cbb47431f0b43b87d42' })
  .then(results => res.json(results))
  .catch(err => res.status(500).json(err));
// result: []

MongoDB console

db.sales.find({ registeredBy: '57ea0cbb47431f0b43b87d42' })
// result: 8 elements

After I modify my schema's property back to ObjectId, the mongoose query works again. Since I need to migrate to a new datatype, I want to be able to query and store both types of values. Is this possible?

Upvotes: 0

Views: 450

Answers (1)

Lance Pollard
Lance Pollard

Reputation: 79208

Good question this is a complicated edge case. I am not super familiar with Mongoose specifically, but one way to do this would be to migrate your data at a lower level. For example, create a mongo script that uses the low-level mongo API to do the migration, something along the lines of:

db.sales.find().forEach(function(doc){
  var user = db.users.find({ _id: doc.registeredBy });
  db.sales.update({ _id: doc._id, }, {
    $set: { registeredBy: user.first + ' ' + user.last }
  });
});

This is similar to what a module like https://github.com/balmasi/migrate-mongoose does, but I've personally found it easier to use mongo scripts on the cli directly.

mongo < sale-schema-migration.js

Upvotes: 1

Related Questions