Navigation

collection.insertOne()

On this page

Definition

collection.insertOne(document)

Inserts a document into a collection. The collection.insertOne() method has the following parameter.

Parameter Type Description
document document A document to insert into the collection.
Returns:A promise that resolves to a JSON object with the following fields:
  • insertedId: the _id of the inserted document

Examples

The following examples assume that the test.example namespace has been added to MongoDB in the Stitch admin console and appropriate rules have been set. See MongoDB Rules for more information.

Inserting a Document

exports = function() {
  const mongodb = context.services.get("mongodb-atlas");
  const collection = mongodb.db("test").collection("example");

  return collection
    .insertOne({x: 1})
    .then(result => {
      const { insertedId } = result;
      // Do something with the insertedId
      return `Inserted document with _id: ${insertedId}`;
   });
};

Handling Write Errors

If a write error occurs, the collection.insertOne() promise rejects with an error message. You can handle write errors by appending .catch() statements to your calls to collection.insertOne().

exports = function() {
  const mongodb = context.services.get("mongodb-atlas");
  const collection = mongodb.db("test").collection("example");

  const tryInsert = doc => {
    return collection
      .insertOne(doc)
      .catch(err => console.error(err.message));
  }

  return tryInsert({ name: "Rick" }).then( ({ insertedId }) => {
    // Insert another document with a duplicate key
    // This promise will reject
    tryInsert({ _id: insertedId, name: "Morty" });
  })
};

The second tryInsert promise rejects with the following duplicate key error message:

Duplicate key error: E11000 duplicate key error collection: test.example index: _id_ dup key: { : ObjectId('5b310cbfb8b9987d0a035fa5') }