-
-
Notifications
You must be signed in to change notification settings - Fork 3.9k
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
Not working nested defaults - findByIdAndUpdate #11668
Comments
Solved the issue? |
nah |
When you set the first document (is not exist) the defaults not inserts if you putting a data to the same object where is field with default located. |
const mongoose = require('mongoose');
const {Schema} = mongoose;
const badSchema = new Schema({
time: {
hit: {type: Number, default: 0},
resolved: { type: Number, default: Date.now}
}
});
const goodSchema = new Schema({
resolved: {type: Number, default: Date.now}
});
const Bad = mongoose.model('Bad', badSchema);
const Good = mongoose.model('Good', goodSchema);
async function run() {
await mongoose.connect('mongodb://localhost:27017');
await mongoose.connection.dropDatabase();
const id = mongoose.Types.ObjectId().toString();
console.log(id);
const bad = await Bad.findByIdAndUpdate({_id: id}, {$set: {'time.hit': Date.now()}}, { new: true, setDefaultsOnInsert: true, upsert: true });
const good = await Good.findByIdAndUpdate({_id: id}, {$set: {'time.hit': Date.now()}}, { new: true, setDefaultsOnInsert: true, upsert: true });
console.log('bad', bad);
console.log('good', good);
console.log('check bad DB', await Bad.findOne());
console.log('check good DB', await Good.findOne());
}
run(); Data in database using compass: Bad:
Good:
|
I faced the same issue here. It's quite useless for a nested default value to work if you can't set other fields at the same nested level of it during the first upserting. |
@donaldshen this issue is fixed, were you on an older version of Mongoose that didn't have this fix? |
Hi there.
When you trying to set a document props by the findByIdAndUpdate method, the default value will not be set into DB if nested (but JSON will be returned).
The latest mongoose ^6.3.0
Needs a patch? or dupe issue? Thanks.
Schemes
It Not Sets
It Sets (for example)
The text was updated successfully, but these errors were encountered: