# Inserting Data

You can insert a record into the collection by calling the add method on the collection object. Returning to the example of a to-do list, assume we want to add a new to-do:

db.collection('todos').add({
  // The data field represents the JSON data to add
  data: {
    // _id:'todo-identifiant-aleatoire', // You can choose a custom _id and use the one automatically assigned by the database in this scenario
    description: "learn cloud database",
    due: new Date("2018-09-01"),
    tags: [
      "cloud",
      "database"
    ],
    // Add a geographical location to the to-do (113°E, 23°N)
    location: new db.Geo.Point(113, 23),
    done: false
  },
  success: function(res) {
    // The res is an object with the _id field, marking the id of the record just created
    console.log(res)
  }
})

Of course, the Promise style is also supported. As long as success, fail, or complete are not passed into the object, the add method returns a Promise:

db.collection('todos').add({
  // The data field represents the JSON data to add
  data: {
    description: "learn cloud database",
    due: new Date("2018-09-01"),
    tags: [
      "cloud",
      "database"
    ],
    location: new db.Geo.Point(113, 23),
    done: false
  }
})
.then(res => {
  console.log(res)
})

The APIs for adding, deleting, querying, and modifying database support both callback style and Promise style calls.

After the creation is successful, we can see the newly added data in the console.

The full API definition can be found in the add API documentation.

In the next chapter, we will learn how to use an API to query the data just inserted.

点击咨询小助手