From 50386359d8439e46561265f9639e901d3acb285e Mon Sep 17 00:00:00 2001 From: Valeri Karpov Date: Sat, 20 May 2017 10:40:58 -0600 Subject: [PATCH] fix(schema): enforce that _id is never null Re: #5236 mongodb/node-mongodb-native#517 --- lib/model.js | 2 +- lib/schema/objectid.js | 3 +++ test/document.test.js | 10 ++++++++++ 3 files changed, 14 insertions(+), 1 deletion(-) diff --git a/lib/model.js b/lib/model.js index 27caf0f4dc0..05a068bad8e 100644 --- a/lib/model.js +++ b/lib/model.js @@ -126,7 +126,7 @@ Model.prototype.$__handleSave = function(options, callback) { var obj = this.toObject(toObjectOptions); - if (!utils.object.hasOwnProperty(obj || {}, '_id')) { + if ((obj || {})._id == null) { // documents must have an _id else mongoose won't know // what to update later if more changes are made. the user // wouldn't know what _id was generated by mongodb either diff --git a/lib/schema/objectid.js b/lib/schema/objectid.js index 6f684191c90..f0dd9fdc42a 100644 --- a/lib/schema/objectid.js +++ b/lib/schema/objectid.js @@ -196,6 +196,9 @@ function defaultId() { } function resetId(v) { + if (v == null) { + return new oid(); + } this.$__._id = null; return v; } diff --git a/test/document.test.js b/test/document.test.js index c8be117e84b..37af387e0fa 100644 --- a/test/document.test.js +++ b/test/document.test.js @@ -4162,6 +4162,16 @@ describe('document', function() { }); }); + it('null _id (gh-5236)', function(done) { + var childSchema = new mongoose.Schema({}); + + var M = db.model('gh5236', childSchema); + + var m = new M({ _id: null }); + assert.ok(m._id); + done(); + }); + it('modify multiple subdoc paths (gh-4405)', function(done) { var ChildObjectSchema = new Schema({ childProperty1: String,