Inserting Records into Collections

Learn how to insert data into MongoDB collections using MeteorJS.

Inserting data into a collection involves putting documents into the MongoDB database. MongoDB doesn’t enforce a schema (a document blueprint for the collection), but it’s important that we structure our documents in ways that reduce the amount of data retrieval code. Later, we’ll write to retrieve data.

Syntax for inserting data

We can insert the data in Meteor.js by writing Mongo.Collection.insert(dataToInsert, callback).

Note: To insert a document, a collection must exist that it can be inserted into.

A callback function has two parameters, which are the error object and the data (return value). If there’s no error, the error object is null. This follows a convention in Node.js that Meteor is built on.

If the insertion is successful, it returns the _id of the inserted document.

Document data types

A document is an object with a field that can be any combination of data types such as arrays, objects, numbers, strings, null, and boolean. Below is an example of a document:

 const document =  {
     name: "Joe Doe", //string
     address: {
       "country" : "Nigeria",
       "state" : "Aba",
       "street" : "No 6 East West Road"
     } //embedded document
    age: 45 // number
    qualification: null //null,
    active: true // boolean,
    skills: ["coding", "writing"] //array
  };

We can insert any structure of data containing varying fields into a collection, but we need to ensure that the data uniformity schema is used. The schema checks the data before passing it for insertion into the database.

Get hands-on with 1200+ tech skills courses.