Skip to content

Commit 5038635

Browse files
committed
fix(schema): enforce that _id is never null
Re: #5236 mongodb/node-mongodb-native#517
1 parent d951bed commit 5038635

File tree

3 files changed

+14
-1
lines changed

3 files changed

+14
-1
lines changed

lib/model.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -126,7 +126,7 @@ Model.prototype.$__handleSave = function(options, callback) {
126126

127127
var obj = this.toObject(toObjectOptions);
128128

129-
if (!utils.object.hasOwnProperty(obj || {}, '_id')) {
129+
if ((obj || {})._id == null) {
130130
// documents must have an _id else mongoose won't know
131131
// what to update later if more changes are made. the user
132132
// wouldn't know what _id was generated by mongodb either

lib/schema/objectid.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,9 @@ function defaultId() {
196196
}
197197

198198
function resetId(v) {
199+
if (v == null) {
200+
return new oid();
201+
}
199202
this.$__._id = null;
200203
return v;
201204
}

test/document.test.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4162,6 +4162,16 @@ describe('document', function() {
41624162
});
41634163
});
41644164

4165+
it('null _id (gh-5236)', function(done) {
4166+
var childSchema = new mongoose.Schema({});
4167+
4168+
var M = db.model('gh5236', childSchema);
4169+
4170+
var m = new M({ _id: null });
4171+
assert.ok(m._id);
4172+
done();
4173+
});
4174+
41654175
it('modify multiple subdoc paths (gh-4405)', function(done) {
41664176
var ChildObjectSchema = new Schema({
41674177
childProperty1: String,

0 commit comments

Comments
 (0)