Or A
Or A

Reputation: 1789

Adding fields to model which derived from Mongoose schema

I have a Mongoose schema that looks like this:

ManifestSchema = new Schema({
entries: [{
            order_id: String,
            line_item: {}, // <-- resolved at run time
            address: {},// <-- resolved at run time
            added_at: Number,
            stop: Number,

        }]

}, {collection: 'manifests', strict: true });

and somewhere in the code I have this:

Q.ninvoke(Manifests.findById(req.params.id), 'exec')
.then(function(manifest)
{
// ... so many things, like resolving the address and the item information
entry.line_item = item;
entry.address = order.delivery.address;
})

The issue that I faced is that without defining address and line_item in the schema, when I resolved them at run time, they wouldn't returned to the user because they weren't in the schema...so I added them...which cause me another unwanted behavior: When I saved the object back, both address and line_item were saved with the manifest object, something that I would like to avoid.

Is there anyway to enable adding fields to the schema at run time, but yet, not saving them on the way back?

I was trying to use 'virtuals' in mongoose, but they really provide what I need because I don't create the model from a schema, but it rather returned from the database.

Upvotes: 1

Views: 990

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311865

Call toObject() on your manifest Mongoose instance to create a plain JavaScript copy that you can add extra fields to for the user response without affecting the doc you need to save:

Q.ninvoke(Manifests.findById(req.params.id), 'exec')
.then(function(manifest)
{
  var manifestResponse = manifest.toObject();

  // ... so many things, like resolving the address and the item information
  entry.line_item = item;
  entry.address = order.delivery.address;
})

Upvotes: 4

Related Questions