-
-
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
Inconsistent behavior default values nested paths using findOneAndUpdate with setDefaultsOnInsert #10232
Comments
|
I took a closer look and this is expected behavior that there's no real workaround for. That's because const findOneAndUpdate2Doc = await Model.findOneAndUpdate(
{ name: 'findOneAndUpdate2' }, { meta: {} }, { new: true, upsert: true, setDefaultsOnInsert: true }); The only potential workaround Mongoose could to would be to add Instead, you should use Mongoose timestamps for this use case as shown below. const mongoose = require('mongoose');
mongoose.set('debug', true);
mongoose.set('useFindAndModify', false);
const schema = new mongoose.Schema({
name: String,
meta: {
created: { type: Date },
},
}, { timestamps: { createdAt: 'meta.created' } });
const Model = mongoose.model('Test', schema);
run().catch(err => console.log(err));
async function run() {
console.log("Mongoose version", mongoose.version);
await mongoose.connect('mongodb://localhost:27017/test', {
useNewUrlParser: true,
useUnifiedTopology: true
});
await mongoose.connection.dropDatabase();
const create1 = { name: 'create1' };
const create2 = { name: 'create2', meta: {} };
const findOneAndUpdate1 = { name: 'findOneAndUpdate1' };
const findOneAndUpdate2 = { name: 'findOneAndUpdate2', meta: {} };
const create1Doc = await Model.create(create1);
const create2Doc = await Model.create(create2);
const findOneAndUpdate1Doc = await Model.findOneAndUpdate(
{ name: 'findOneAndUpdate1' }, findOneAndUpdate1, { new: true, upsert: true, setDefaultsOnInsert: true });
const findOneAndUpdate2Doc = await Model.findOneAndUpdate(
{ name: 'findOneAndUpdate2' }, findOneAndUpdate2, { new: true, upsert: true, setDefaultsOnInsert: true });
console.log(create1Doc, create2Doc, findOneAndUpdate1Doc, findOneAndUpdate2Doc);
const db1 = await Model.findOne({name:'findOneAndUpdate1'}).lean();
console.log(db1);
const db2 = await Model.findOne({name:'findOneAndUpdate2'}).lean();
console.log(db2);
} |
Mongoose version: 5.12.8
Reproduction script (drops existing
test
DB on local):Console output:
DB:
Expected behavior: Every document has meta.created.
Actual behavior: Every document returned by Mongoose has meta.created, but in DB
findOneAndUpdate2
is missing meta.created.The text was updated successfully, but these errors were encountered: