Inserting documents

The native types are String, Number, Boolean, Date and null. You can also usearrays and subdocuments (objects). If a field is undefined, it will not be saved (this is different fromMongoDB which transforms undefined in null, something I find counter-intuitive).

If the document does not contain an _id field, NeDB will automatically generated one for you (a 16-characters alphanumerical string). The _id of a document, once set, cannot be modified.

Field names cannot begin by '$' or contain a '.'.

  1. var doc = { hello: 'world'
  2. , n: 5
  3. , today: new Date()
  4. , nedbIsAwesome: true
  5. , notthere: null
  6. , notToBeSaved: undefined // Will not be saved
  7. , fruits: [ 'apple', 'orange', 'pear' ]
  8. , infos: { name: 'nedb' }
  9. };
  10. db.insert(doc, function (err, newDoc) { // Callback is optional
  11. // newDoc is the newly inserted document, including its _id
  12. // newDoc has no key called notToBeSaved since its value was undefined
  13. });

You can also bulk-insert an array of documents. This operation is atomic, meaning that if one insert fails due to a unique constraint being violated, all changes are rolled back.

  1. db.insert([{ a: 5 }, { a: 42 }], function (err, newDocs) {
  2. // Two documents were inserted in the database
  3. // newDocs is an array with these documents, augmented with their _id
  4. });
  5. // If there is a unique constraint on field 'a', this will fail
  6. db.insert([{ a: 5 }, { a: 42 }, { a: 5 }], function (err) {
  7. // err is a 'uniqueViolated' error
  8. // The database was not modified
  9. });