Add `omitUndefined` to docs for `updateX()` and `findOneAndUpdate()`
The problem I met here is that the behavior of saving and updating null or undefined is confused to me.
Here is my example code. I try to save and update the same document with undefined value in the document.
var mongoose = require('mongoose');
var schema = new mongoose.Schema({
name: {
type: String
},
nickName: {
type: String
},
sibilings: {
name: String
}
});
var model = mongoose.model("person", schema);
mongoose.connect("mongodb://127.0.0.1/test2", function () {
console.log('connect to local mongodb');
mongoose.connection.db.dropCollection("people");
var doc = new model({
name: "Steven",
nickName: undefined,
siblings: undefined,
});
doc.save(function (err, doc) {
console.log(doc)
model.update({
_id: doc._id
}, {
$set: {
name: "John",
nickName: undefined,
siblings: undefined
}
}, function (err) {
model.find({
_id: doc._id
}, function (err, doc){
console.log(doc);
})
});
});
});
and the output of console is
{ siblings: {},
_id: 56284e3ec4f126f75ba909ab,
nickName: undefined,
name: 'Steven',
__v: 0 }
[ { sibilings: null,
nickName: null,
name: 'John',
_id: 56284e3ec4f126f75ba909ab,
__v: 0 } ]
There are two problems:
- the first
console.logshows that thesiblingsis an empty object, but we actually assignedundefinedto it. - the second console.log
siblingsandnickNamebecome null object in mongodb and thenullis actual existent in the db when you query it through CLI. The second console.log is quite different from previous one.
If this is an expected behavior, I am just wondering the rational under the hood. If it's not, is it possible that the mongoose just filtered out the null and undefined?
Thanks.
It's unfortunately expected behavior, see https://github.com/mongodb/js-bson/issues/134. The bson type undefined has been deprecated for years, so js-bson doesn't support it and just transforms undefined to null under the hood.
@vkarpov15 Thanks for response. Besides the undefined to null transformation, there is still the different behavior problem. As you can see, in the first query, somehow mongoose just filtered out the undefined property, but in the second query the mongoose just bypass undefined to mongodb.
Isn't it better if we also filter out the undefined in second query?
The first console.log() just outputs the document as it was before it was save()-ed, mongoose doesn't update doc with what the db actually stored.
Also, can you clarify what you mean by "filter out the undefined in the second query"? I don't understand.
What's the best practice then for unique fields with sparse indexes that can be undefined on create / update?
@kilianc I don't understand your question, can you please clarify?
const data = someThingElse()
Model.create(data)
where data could be:
{ foo: undefined, hello: 5 }
My understanding is that this will fail with two docs with foo: undefined
No, mongoose will strip out keys whose value is undefined, because the mongodb driver doesn't support that properly (it stores undefined keys as nulls)
If you want to 'strip' a field from a document. You need to get the document, set the property undefined, and then save the document.
// NOTE: written in the async await pattern. the get set save approach will work with any pattern
// ... require stuff
// wrapper for async pattern
const asyncWrap = fn => (...args) => fn(...args).catch(args[2]);
// demo route
router.post('/some/api/endpoint/', asyncWrap(demo_endpoint));
// some endpoint (module.exports hopefully)
let demo_endpoint = async function(req, res) {
// get the document in your application
let doc = await new Promise((resolve, reject) => {
Model.findOne({ _id: id }, (err, doc) => {
if (err) return reject(err);
return resolve(doc);
});
});
// set the property to undefined
doc.property = undefined;
// save the document
let saved = await new Promise((resolve, reject) => {
doc.save((err) => {
if (err) return reject(err);
return resolve();
});
});
// continue coding...
};
This is the only way I've found to actually strip a field from a document. The update $set method will convert undefined into a null property. Hope this helps.
I was confused by the way save() and update() handle undefined values differently. I also realized that because bson type does not support undefined, mongodb can only convert the value from undefined to null. However, I wonder if you can ignore the undefined value in mongoose to maintain consistency between save() and update().
const mongoose = require('mongoose')
const UndefinedTest = mongoose.model('UndefinedTest', new mongoose.Schema({
name: String,
job: String,
family: {
name: String,
age: Number
},
}));
(() => {
mongoose.connect('mongodb://localhost/dev', {
useNewUrlParser: true
}, async (err) => {
const db = mongoose.connection
await UndefinedTest.deleteMany({})
const saveData = {
name: 'Reid',
job: undefined,
family: {
name: undefined,
age: 17
}
}
await new UndefinedTest(saveData).save()
const saveDoc = await UndefinedTest.find({ name: 'Reid' }).lean()
console.log('Create a document with undefined fiels')
console.table(saveDoc)
const updateData = {
job: undefined,
family: {
name: undefined,
age: 27
}
}
await UndefinedTest.findOneAndUpdate({ name: 'Reid' }, { $set: updateData })
const updateDoc = await UndefinedTest.find({ name: 'Reid' }).lean()
console.log('Update the document with undefined fiels')
console.table(updateDoc)
await db.close()
})
})()
Create a document with undefined fiels
┌─────────┬──────────────────────────┬────────┬─────────────┬─────┐
│ (index) │ _id │ name │ family │ __v │
├─────────┼──────────────────────────┼────────┼─────────────┼─────┤
│ 0 │ 5c947208fb19935055d655cf │ 'Reid' │ { age: 17 } │ 0 │
└─────────┴──────────────────────────┴────────┴─────────────┴─────┘
Update the document with undefined fiels
┌─────────┬──────────────────────────┬────────┬─────────────────────────┬─────┬──────┐
│ (index) │ _id │ name │ family │ __v │ job │
├─────────┼──────────────────────────┼────────┼─────────────────────────┼─────┼──────┤
│ 0 │ 5c947208fb19935055d655cf │ 'Reid' │ { name: null, age: 27 } │ 0 │ null │
└─────────┴──────────────────────────┴────────┴─────────────────────────┴─────┴──────┘