Skip to content

Commit

Permalink
fix: Elegantly handle insert() and create() with upsert: true and no …
Browse files Browse the repository at this point in the history
…_id specified.
  • Loading branch information
notheotherben committed Feb 8, 2017
1 parent 3990aa5 commit 81e69c0
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/Model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -497,7 +497,7 @@ export class Model<TDocument extends { _id?: any }, TInstance> {
let docs = this._handlers.creatingDocuments(objects);
return docs.map((object: { _id: any; }) => {
return new Bluebird<any[]>((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) => {
Expand Down
8 changes: 8 additions & 0 deletions test/Model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(<any>{ answer: "wrong" })).to.eventually.be.rejected;
});
Expand Down Expand Up @@ -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(<any>{ answer: "wrong" })).to.eventually.be.rejected;
});
Expand Down

0 comments on commit 81e69c0

Please sign in to comment.