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
Mongoose not saving nested documents #12398
Comments
const mongoose = require('mongoose');
const aSchema = new mongoose.Schema({
name: String
});
const bSchema = new mongoose.Schema({
persons: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'A'
}]
});
const A = mongoose.model('A', aSchema);
const B = mongoose.model('B', bSchema);
async function run() {
await mongoose.connect('mongodb://localhost:27017');
await mongoose.connection.dropDatabase();
const person1 = await A.create({ name: 'Test Testerson' });
const person2 = await A.create({ name: 'Test' });
const id = person2._id;
await B.create({ persons: [person1._id, person2._id] });
const test = await B.findOne().populate('persons');
console.log(test);
test.persons.find(x => x._id.toString() === id.toString()).name = 'Value Changed';
await test.save();
// await test.persons[0].save();
// await test.persons[1].save();
const res = await B.findOne().populate('persons');
console.log(res);
}
run(); |
Populated docs are different from subdocs. If you set a populated value, you need to call save on the doc. |
Could you explain the difference between a ref and a subdocument? @IslandRhythms |
A ref indicates what Model populate should look at when querying the indicated path. A subdocument is described in the image you attached to this issue. |
@jamesbruice when you populate a |
docs(subdocs): clarify that populated docs are not subdocs
Prerequisites
Mongoose version
5.12.14
Node.js version
v16.13.1
MongoDB server version
5.0.11
Description
When modifying a field on a populated document, changes should be saved, when saving the parent.
This is not occ, instead I need to save the document myself (see Steps to Reproduce)
Steps to Reproduce
Schemas
route to change name
Expected Behavior
https://mongoosejs.com/docs/subdocs.html#subdocuments
Saving the tasks individually should not be required. They should be saved when the parent is being saved
The text was updated successfully, but these errors were encountered: