diff --git a/lib/Model.ts b/lib/Model.ts index 6947221..a35e073 100644 --- a/lib/Model.ts +++ b/lib/Model.ts @@ -497,7 +497,7 @@ export class Model { let docs = this._handlers.creatingDocuments(objects); return docs.map((object: { _id: any; }) => { return new Bluebird((resolve, reject) => { - this.collection.findOneAndUpdate({ _id: object._id }, object, { + this.collection.findOneAndUpdate({ _id: object._id || { $exists: false }}, object, { upsert: options.upsert, returnOriginal: false }, (err, result) => { diff --git a/test/Model.ts b/test/Model.ts index 51a6b22..56b3345 100644 --- a/test/Model.ts +++ b/test/Model.ts @@ -217,6 +217,10 @@ describe("Model",() => { return chai.expect(model.create({ answer: 14 }, { upsert: true })).to.eventually.exist; }); + it("should generate an _id for new, upserted, documents", () => { + return chai.expect(model.create({ answer: 12 }, { upsert: true })).to.eventually.exist.and.have.property("_id").and.exist; + }) + it("should return an error if you don't meet the schema validation requirements",() => { return chai.expect(model.create({ answer: "wrong" })).to.eventually.be.rejected; }); @@ -265,6 +269,10 @@ describe("Model",() => { return chai.expect(model.insert({ answer: 14 }, { upsert: true })).to.eventually.exist; }); + it("should generate an _id for new, upserted, documents", () => { + return chai.expect(model.insert({ answer: 12 }, { upsert: true })).to.eventually.exist.and.have.property("_id").and.exist; + }) + it("should return an error if you don't meet the schema validation requirements",() => { return chai.expect(model.insert({ answer: "wrong" })).to.eventually.be.rejected; });