createObject

Collection.createObject(dbApiKey, collectionName, objectJSON[, token])

Creates a new object in a collection.

Parameters

The method has the following parameters:

ParameterDescriptionRequired
dbApiKeyDatabase API key.Yes.
collectionNameCollection name in which to create a new object.Yes.
objectJSONJSON object with the content of the new object based on collection structure.Yes.
tokenSession token or database master key. Required if the collection has security enabled.No.

Response

Response for a successfully created object (regardless of the data used to create the object).

ParameterDescription
_idID of the object created.
_createdAtDate when the object was created.
{
	_id: '5783eb10975afbb10a042f0c',
	_createdAt: {
		'$date': '2016-07-11T18:53:04.287Z'
	}
}
Examples

Create a new object in the Student collection:

var dbApiKey = "c33010af-f263-4443-9897-c2ffaf522956";
var result = Collection.createObject(dbApiKey, "Student", {
  "firstName": "James",
  "lastName": "Brown",
  "isTransferStudent": true,
  "courses":[100, 101],
  "major": {"name":"Chemistry"}, 
  "toAddress": {"collName": "Address", "_id": "57a52992e4b03647ddae32a8"}
});
{
	"_id": "57a52a1be4b0288ba31f1833",
	"_createdAt": {
		"$date": "2016-08-06T00:06:51.407Z"
	}
}
This example shows how to get the ID of the object created:
var dbApiKey = "c33010af-f263-4443-9897-c2ffaf522956";
var result = Collection.createObject(dbApiKey, "Student", {
  "firstName": "James",
  "lastName": "Brown",
  "isTransferStudent": true,
  "courses":[100, 101],
  "major": {"name":"Chemistry"}, 
  "toAddress": {"collName": "Address", "_id": "57a52992e4b03647ddae32a8"}
})._id;
Another example with additional data types:
var result = Collection.createObject(dbApiKey, "BigCollection", {
  "text": "Hello World",
  "number": "1000",
  "date": (new Date()).toISOString(), 
  "array": [1,2,3,4,5],
  "object": {"value1":"hello", "value2":"world"}, 
  "location": [40.7128, -74.0059]
});
This example also includes a user session in the createObject method after user login. If you have enabled ACL for this database collection, and set the default ACL to @Creator, then the ACL column will be automatically filled with the current signed in users ID.

var user = DatabaseUser.login(dbApiKey, "amy", "123");
console.log(user.sessionToken);
var result = Collection.createObject(dbApiKey, "Students", {
  "firstName": "Anna",
  "lastName": "Lee",
  "isTransferStudent": false
}, user.sessionToken);