Skip to content

Commit

Permalink
feat(model): add insertOne() function to insert a single doc
Browse files Browse the repository at this point in the history
Fix #14843
  • Loading branch information
vkarpov15 committed Jan 6, 2025
1 parent 03343ad commit 3203fe1
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 0 deletions.
43 changes: 43 additions & 0 deletions lib/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -2774,6 +2774,49 @@ Model.create = async function create(doc, options) {
return res;
};

/**
* Shortcut for saving one document to the database.
* `MyModel.insertOne(obj, options)` is almost equivalent to `new MyModel(obj).save(options)`.
* The difference is that `insertOne()` checks if `obj` is already a document, and checks for discriminators.
*
* This function triggers the following middleware.
*
* - `save()`
*
* #### Example:
*
* // Insert one new `Character` document
* await Character.insertOne({ name: 'Jean-Luc Picard' });
*
* // Create a new character within a transaction.
* await Character.insertOne({ name: 'Jean-Luc Picard' }, { session });
*
* @param {Object|Document} docs Document to insert, as a POJO or Mongoose document
* @param {Object} [options] Options passed down to `save()`.
* @return {Promise}
* @api public
*/

Model.insertOne = async function insertOne(doc, options) {
_checkContext(this, 'insertOne');

const discriminatorKey = this.schema.options.discriminatorKey;
const Model = this.discriminators && doc[discriminatorKey] != null ?
this.discriminators[doc[discriminatorKey]] || getDiscriminatorByValue(this.discriminators, doc[discriminatorKey]) :
this;
if (Model == null) {
throw new MongooseError(
`Discriminator "${doc[discriminatorKey]}" not found for model "${this.modelName}"`
);
}
let toSave = doc;
if (!(toSave instanceof Model)) {
toSave = new Model(toSave);
}

return await toSave.$save(options);
};

/**
* _Requires a replica set running MongoDB >= 3.6.0._ Watches the
* underlying collection for changes using
Expand Down
31 changes: 31 additions & 0 deletions test/model.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -8461,6 +8461,37 @@ describe('Model', function() {
assert.deepStrictEqual(toDrop, []);
});
});

describe('insertOne() (gh-14843)', function() {
it('should insert a new document', async function() {
const userSchema = new Schema({
name: String
});
const User = db.model('User', userSchema);

const res = await User.insertOne({ name: 'John' });
assert.ok(res instanceof User);

const doc = await User.findOne({ _id: res._id });
assert.equal(doc.name, 'John');
});

it('should support validateBeforeSave: false option', async function() {
const userSchema = new Schema({
name: {
type: String,
required: true
}
});
const User = db.model('User', userSchema);

const res = await User.insertOne({}, { validateBeforeSave: false });
assert.ok(res instanceof User);

const doc = await User.findOne({ _id: res._id });
assert.equal(doc.name, undefined);
});
});
});


Expand Down

0 comments on commit 3203fe1

Please sign in to comment.