Hello,
I’m working with Mongoose in a Node.js application and have encountered a situation where I’m not entirely sure about the expected impact of using .save() on a document that has been partially loaded with a projection.
Here’s a simple code snippet illustrating my scenario:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const mySchema = new Schema({
field1: String,
field2: String,
field3: String
// ... other fields ...
});
const MyModel = mongoose.model('MyModel', mySchema);
// Finding a document with a projection
MyModel.find({}, 'field1 field2').exec(function (err, docs) {
if (err) {
// handle error
console.error(err);
} else {
let doc = docs[0];
// Update some of the projected fields
doc.field1 = 'new value for field1';
// Save the document
doc.save(function (saveErr) {
if (saveErr) {
// handle save error
console.error(saveErr);
} else {
console.log('Document saved successfully.');
}
});
}
});
In this example, I’m querying for documents but only projecting field1 and field2. After modifying one of these projected fields, I use .save() to update the document.
My question is: What happens to the other fields (like field3) that were not included in the projection? Will they remain unchanged in the database, or does saving the partial document in some way affect these non-projected fields?
I haven’t explicitly set any strict options in my schema, and I’m observing that the non-projected fields seem to remain unchanged. However, I want to confirm if this is the expected behavior and if it’s safe to rely on this in production environments.
Thank you