-
-
Notifications
You must be signed in to change notification settings - Fork 3.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
How to programmatically create a new subdocument from outside document? #9076
Comments
Document arrays have a 'use strict';
const mongoose = require('mongoose');
mongoose.set('useFindAndModify', false);
const { Schema } = mongoose;
run().catch(err => console.log(err));
async function run() {
await mongoose.connect('mongodb://localhost:27017/test', {
useNewUrlParser: true,
useUnifiedTopology: true
});
await mongoose.connection.dropDatabase();
const nestedSchema = new Schema({ name: String });
nestedSchema.methods.getAnswer = () => 42;
const schema = new Schema({
arr: [nestedSchema]
});
const Model = mongoose.model('Test', schema);
const doc = new Model({ arr: [] });
const subdoc = doc.arr.create({ name: 'foo' });
console.log(subdoc instanceof mongoose.Document); // true
console.log(subdoc.getAnswer()); // 42
} But I've struggled to find a case where this is useful. Can you elaborate on your use case for this? |
Yes, see my comment/solution here: mblarsen/mongoose-hidden#58 (comment) |
@niftylettuce I took a closer look at this, it looks like your issue won't be solved by 'use strict';
const mongoose = require('mongoose');
mongoose.set('useFindAndModify', false);
const { Schema } = mongoose;
run().catch(err => console.log(err));
async function run() {
await mongoose.connect('mongodb://localhost:27017/test', {
useNewUrlParser: true,
useUnifiedTopology: true
});
await mongoose.connection.dropDatabase();
const nestedSchema = new Schema({ name: String });
nestedSchema.methods.getAnswer = () => 42;
const schema = new Schema({
arr: [nestedSchema],
singleNested: nestedSchema
});
const Model = mongoose.model('Test', schema);
// Cast to doc array
let subdoc = Model.schema.path('arr').cast([{ name: 'foo' }])[0];
console.log(subdoc instanceof mongoose.Document); // true
console.log(subdoc.getAnswer()); // 42
// Cast to single nested subdoc
subdoc = Model.schema.path('singleNested').cast({ name: 'bar' });
console.log(subdoc instanceof mongoose.Document); // true
console.log(subdoc.getAnswer()); // 42
} More on schematypes: https://mongoosejs.com/docs/schematypes.html |
For example, the only way right now that is documented to create a subdocument is:
I think it might be nice to document, if possible, a way to create the
subDocument
without having to create an instance of the model?The text was updated successfully, but these errors were encountered: