The easiest way that we can add a new row to a collection in our MongoDB is to use Model.create({})
.
If we want to add a row (you can think of row as meaning "new data") to our collection Name we could write:
Name.create({write the column names and values here});
Inside {}
, we write whatever data that we want to add to our collection.
Example
Name.create({firstName:"John", lastName:"Smith"});
That would add a Name of {firstName: “John”, lastName: “Smith”} to our collection Name.
Checking Datatypes
By default, MongoDB doesn’t actually help us check data types. The way that we can make sure that we get the correct data type inside is by setting up our Model Schema properly.
There, we specify what kind of data every column must be. If we have the wrong data type, our new data won't get added to our collection.
We wouldn't, for example, be able to add a "fdsjkljlfd" to an integer column.
Another example, if we were also to add a column of random number with data type of Number to our above example such that instead we now have three columns(firstName, lastName and ranNum):
The following code would fail because ranNum must be an integer.
Name.create({firstName:"firstName", lastName:"lastName", ranNum:"ranNum"});
If any of the columns have the wrong data type, the entire row will not be added.
In Summary
To create a new row(a new piece of data) for any collection in MongoDB, we use ModelName.create({}) and inside of {}
is where we write our data(this data structure by the way is called a JSON). And inside of {}, we add columnname1: columnvalue1, columnname2: columnvalue2...etc as needed.