In the mongoose docs, under the Defining Schemas section the docs state:
If you want to add additional keys later, use the Schema#add method.
I want to understand: Is there a difference between using Schema.prototype.add() and simply updating the schema?
@govindrai the instance of Schema that is returned by new Schema
has several properties that are set based on the properties of the object passed into new Schema
. The two most relevant to your question are paths
, and tree
. The add command basically calls the path
method on each path/nested path which updates the paths and tree properties of the schema.
Here is an example that will hopefully clarify this:
note that the something
path is not set in the saved document
#!/usr/bin/env node
'use strict';
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
const conn = mongoose.connection;
const Schema = mongoose.Schema;
const schema = new Schema({
name: String
});
schema.something = Number; // is this what you meant by updating the schema?
schema.add({ somethingElse: Number });
schema.path('thirdThing', { type: Number });
const Test = mongoose.model('test', schema);
const test = new Test({
name: 'Billy',
something: 34,
somethingElse: 23,
thirdThing: 12
});
async function run() {
await conn.dropDatabase();
await test.save();
let found = await Test.findOne({});
console.log(found);
return conn.close();
}
run();
issues: ./6533.js
{ _id: 5b0d37184ebd4721d5fcc7a8,
name: 'Billy',
somethingElse: 23,
thirdThing: 12,
__v: 0 }
issues:
Please let me know if I misunderstood your question :smile: . I hope this helps.
@govindrai what do you mean by "simply updating the schema"? If you do new Schema({ foo: String, bar: String })
and you change it to new Schema({ foo: String, bar: String, baz: String })
, there's no difference between that and new Schema({ foo: String, bar: String }).add({ baz: String })
as far as mongoose is concerned.
Most helpful comment
@govindrai the instance of Schema that is returned by
new Schema
has several properties that are set based on the properties of the object passed intonew Schema
. The two most relevant to your question arepaths
, andtree
. The add command basically calls thepath
method on each path/nested path which updates the paths and tree properties of the schema.Here is an example that will hopefully clarify this:
note that the
something
path is not set in the saved document6533.js
Output:
Please let me know if I misunderstood your question :smile: . I hope this helps.