Underscore.js _.extend function does not copy mongoose model properties when they are not defined in the schema? Underscore.js _.extend function does not copy mongoose model properties when they are not defined in the schema? mongoose mongoose

Underscore.js _.extend function does not copy mongoose model properties when they are not defined in the schema?


This is happening because if something is not in the schema then Mongoose cannot use 'defineProperty', and this treats the assignment like any other.

So first off, just to be clear.

node = _.extend(node, {"EXTENDNOTinSchema":"TRUE"});

is identical to this:

node['EXTENDNOTinSchema'] = 'TRUE';

Which is entirely different from this, in the general case.

node.set("SETNOTinSchema","TRUE");

The trick is that Mongoose is smart, and using the defineProperty function I mentioned above, it can bind a function to get called for things like this:

node['INSCHEMA'] = 'something';

But for things that are not in the schema, it cannot do this, so the assignment works like a normal assignment.

The part that tripping you up I think is that console.log is doing some hidden magic. If you look at the docs, console.log will call the inspect method of an object that is passed to it. In the case of Mongoose, it's models do not store attributes directly on the model object, they are stored on an internal property. When you assign to a property being watched with defineProperty or call set, it stores the value on the internal object. When you log the model, inspect prints out the internal model contents, making it seem like the model values are stored right on the object.

So when you do

console.log(node);

what you are really seeing is

console.log(node.somehiddenproperty);

So the answer to your question is really, if you have a bunch of values that are not in the schema, you cannot use _.extend. Instead, just use set because it takes an object anyway.

node.set({"EXTENDNOTinSchema":"TRUE"});