[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-3385":3},{"id":4,"name":5,"fullName":6,"owner":7,"repo":5,"description":8,"homepage":9,"htmlUrl":10,"language":11,"languages":10,"totalLinesOfCode":10,"stars":12,"forks":13,"watchers":14,"openIssues":15,"contributorsCount":16,"subscribersCount":16,"size":16,"stars1d":16,"stars7d":16,"stars30d":17,"stars90d":16,"forks30d":16,"starsTrendScore":16,"compositeScore":18,"rankGlobal":10,"rankLanguage":10,"license":19,"archived":20,"fork":20,"defaultBranch":21,"hasWiki":22,"hasPages":20,"topics":23,"createdAt":10,"pushedAt":10,"updatedAt":24,"readmeContent":25,"aiSummary":26,"trendingCount":16,"starSnapshotCount":16,"syncStatus":17,"lastSyncTime":27,"discoverSource":28},3385,"nedb","louischatriot\u002Fnedb","louischatriot","The JavaScript Database, for Node.js, nw.js, electron and the browser","",null,"JavaScript",13543,1016,241,170,0,2,69.22,"MIT License",false,"master",true,[],"2026-06-12 04:00:17","\u003Cimg src=\"http:\u002F\u002Fi.imgur.com\u002F9O1xHFb.png\" style=\"width: 25%; height: 25%; float: left;\">\n\n## The JavaScript Database\n\n> :warning: :warning: :warning: **WARNING:** this library is no longer maintained, and may have bugs and security issues. Feel free to fork but no pull request or security alert will be answered.\n\n\n**Embedded persistent or in memory database for Node.js, nw.js, Electron and browsers, 100% JavaScript, no binary dependency**. API is a subset of MongoDB's and it's \u003Ca href=\"#speed\">plenty fast\u003C\u002Fa>.\n\n**IMPORTANT NOTE**: Please don't submit issues for questions regarding your code. Only actual bugs or feature requests will be answered, all others will be closed without comment. Also, please follow the \u003Ca href=\"#bug-reporting-guidelines\">bug reporting guidelines\u003C\u002Fa> and check the \u003Ca href=\"https:\u002F\u002Fgithub.com\u002Flouischatriot\u002Fnedb\u002Fwiki\u002FChange-log\" target=\"_blank\">change log\u003C\u002Fa> before submitting an already fixed bug :)\n\n\n## Installation, tests\nModule name on npm and bower is `nedb`.\n\n```\nnpm install nedb --save    # Put latest version in your package.json\nnpm test                   # You'll need the dev dependencies to launch tests\nbower install nedb         # For the browser versions, which will be in browser-version\u002Fout\n```\n\n## API\nIt is a subset of MongoDB's API (the most used operations).\n\n* \u003Ca href=\"#creatingloading-a-database\">Creating\u002Floading a database\u003C\u002Fa>\n* \u003Ca href=\"#persistence\">Persistence\u003C\u002Fa>\n* \u003Ca href=\"#inserting-documents\">Inserting documents\u003C\u002Fa>\n* \u003Ca href=\"#finding-documents\">Finding documents\u003C\u002Fa>\n  * \u003Ca href=\"#basic-querying\">Basic Querying\u003C\u002Fa>\n  * \u003Ca href=\"#operators-lt-lte-gt-gte-in-nin-ne-exists-regex\">Operators ($lt, $lte, $gt, $gte, $in, $nin, $ne, $exists, $regex)\u003C\u002Fa>\n  * \u003Ca href=\"#array-fields\">Array fields\u003C\u002Fa>\n  * \u003Ca href=\"#logical-operators-or-and-not-where\">Logical operators $or, $and, $not, $where\u003C\u002Fa>\n  * \u003Ca href=\"#sorting-and-paginating\">Sorting and paginating\u003C\u002Fa>\n  * \u003Ca href=\"#projections\">Projections\u003C\u002Fa>\n* \u003Ca href=\"#counting-documents\">Counting documents\u003C\u002Fa>\n* \u003Ca href=\"#updating-documents\">Updating documents\u003C\u002Fa>\n* \u003Ca href=\"#removing-documents\">Removing documents\u003C\u002Fa>\n* \u003Ca href=\"#indexing\">Indexing\u003C\u002Fa>\n* \u003Ca href=\"#browser-version\">Browser version\u003C\u002Fa>\n\n### Creating\u002Floading a database\nYou can use NeDB as an in-memory only datastore or as a persistent datastore. One datastore is the equivalent of a MongoDB collection. The constructor is used as follows `new Datastore(options)` where `options` is an object with the following fields:\n\n* `filename` (optional): path to the file where the data is persisted. If left blank, the datastore is automatically considered in-memory only. It cannot end with a `~` which is used in the temporary files NeDB uses to perform crash-safe writes.\n* `inMemoryOnly` (optional, defaults to `false`): as the name implies.\n* `timestampData` (optional, defaults to `false`): timestamp the insertion and last update of all documents, with the fields `createdAt` and `updatedAt`. User-specified values override automatic generation, usually useful for testing.\n* `autoload` (optional, defaults to `false`): if used, the database will automatically be loaded from the datafile upon creation (you don't need to call `loadDatabase`). Any command issued before load is finished is buffered and will be executed when load is done.\n* `onload` (optional): if you use autoloading, this is the handler called after the `loadDatabase`. It takes one `error` argument. If you use autoloading without specifying this handler, and an error happens during load, an error will be thrown.\n* `afterSerialization` (optional): hook you can use to transform data after it was serialized and before it is written to disk. Can be used for example to encrypt data before writing database to disk. This function takes a string as parameter (one line of an NeDB data file) and outputs the transformed string, **which must absolutely not contain a `\\n` character** (or data will be lost).\n* `beforeDeserialization` (optional): inverse of `afterSerialization`. Make sure to include both and not just one or you risk data loss. For the same reason, make sure both functions are inverses of one another. Some failsafe mechanisms are in place to prevent data loss if you misuse the serialization hooks: NeDB checks that never one is declared without the other, and checks that they are reverse of one another by testing on random strings of various lengths. In addition, if too much data is detected as corrupt, NeDB will refuse to start as it could mean you're not using the deserialization hook corresponding to the serialization hook used before (see below).\n* `corruptAlertThreshold` (optional): between 0 and 1, defaults to 10%. NeDB will refuse to start if more than this percentage of the datafile is corrupt. 0 means you don't tolerate any corruption, 1 means you don't care.\n* `compareStrings` (optional): function compareStrings(a, b) compares\n  strings a and b and return -1, 0 or 1. If specified, it overrides\ndefault string comparison which is not well adapted to non-US characters\nin particular accented letters. Native `localCompare` will most of the\ntime be the right choice\n* `nodeWebkitAppName` (optional, **DEPRECATED**): if you are using NeDB from whithin a Node Webkit app, specify its name (the same one you use in the `package.json`) in this field and the `filename` will be relative to the directory Node Webkit uses to store the rest of the application's data (local storage etc.). It works on Linux, OS X and Windows. Now that you can use `require('nw.gui').App.dataPath` in Node Webkit to get the path to the data directory for your application, you should not use this option anymore and it will be removed.\n\nIf you use a persistent datastore without the `autoload` option, you need to call `loadDatabase` manually.\nThis function fetches the data from datafile and prepares the database. **Don't forget it!** If you use a\npersistent datastore, no command (insert, find, update, remove) will be executed before `loadDatabase`\nis called, so make sure to call it yourself or use the `autoload` option.\n\nAlso, if `loadDatabase` fails, all commands registered to the executor afterwards will not be executed. They will be registered and executed, in sequence, only after a successful `loadDatabase`.\n\n```javascript\n\u002F\u002F Type 1: In-memory only datastore (no need to load the database)\nvar Datastore = require('nedb')\n  , db = new Datastore();\n\n\n\u002F\u002F Type 2: Persistent datastore with manual loading\nvar Datastore = require('nedb')\n  , db = new Datastore({ filename: 'path\u002Fto\u002Fdatafile' });\ndb.loadDatabase(function (err) {    \u002F\u002F Callback is optional\n  \u002F\u002F Now commands will be executed\n});\n\n\n\u002F\u002F Type 3: Persistent datastore with automatic loading\nvar Datastore = require('nedb')\n  , db = new Datastore({ filename: 'path\u002Fto\u002Fdatafile', autoload: true });\n\u002F\u002F You can issue commands right away\n\n\n\u002F\u002F Type 4: Persistent datastore for a Node Webkit app called 'nwtest'\n\u002F\u002F For example on Linux, the datafile will be ~\u002F.config\u002Fnwtest\u002Fnedb-data\u002Fsomething.db\nvar Datastore = require('nedb')\n  , path = require('path')\n  , db = new Datastore({ filename: path.join(require('nw.gui').App.dataPath, 'something.db') });\n\n\n\u002F\u002F Of course you can create multiple datastores if you need several\n\u002F\u002F collections. In this case it's usually a good idea to use autoload for all collections.\ndb = {};\ndb.users = new Datastore('path\u002Fto\u002Fusers.db');\ndb.robots = new Datastore('path\u002Fto\u002Frobots.db');\n\n\u002F\u002F You need to load each database (here we do it asynchronously)\ndb.users.loadDatabase();\ndb.robots.loadDatabase();\n```\n\n### Persistence\nUnder the hood, NeDB's persistence uses an append-only format, meaning that all updates and deletes actually result in lines added at the end of the datafile, for performance reasons. The database is automatically compacted (i.e. put back in the one-line-per-document format) every time you load each database within your application.\n\nYou can manually call the compaction function with `yourDatabase.persistence.compactDatafile` which takes no argument. It queues a compaction of the datafile in the executor, to be executed sequentially after all pending operations. The datastore will fire a `compaction.done` event once compaction is finished.\n\nYou can also set automatic compaction at regular intervals with `yourDatabase.persistence.setAutocompactionInterval(interval)`, `interval` in milliseconds (a minimum of 5s is enforced), and stop automatic compaction with `yourDatabase.persistence.stopAutocompaction()`.\n\nKeep in mind that compaction takes a bit of time (not too much: 130ms for 50k records on a typical development machine) and no other operation can happen when it does, so most projects actually don't need to use it.\n\nCompaction will also immediately remove any documents whose data line has become corrupted, assuming that the total percentage of all corrupted documents in that database still falls below the specified `corruptAlertThreshold` option's value.\n\nDurability works similarly to major databases: compaction forces the OS to physically flush data to disk, while appends to the data file do not (the OS is responsible for flushing the data). That guarantees that a server crash can never cause complete data loss, while preserving performance. The worst that can happen is a crash between two syncs, causing a loss of all data between the two syncs. Usually syncs are 30 seconds appart so that's at most 30 seconds of data. \u003Ca href=\"http:\u002F\u002Foldblog.antirez.com\u002Fpost\u002Fredis-persistence-demystified.html\" target=\"_blank\">This post by Antirez on Redis persistence\u003C\u002Fa> explains this in more details, NeDB being very close to Redis AOF persistence with `appendfsync` option set to `no`.\n\n\n### Inserting documents\nThe native types are `String`, `Number`, `Boolean`, `Date` and `null`. You can also use\narrays and subdocuments (objects). If a field is `undefined`, it will not be saved (this is different from \nMongoDB which transforms `undefined` in `null`, something I find counter-intuitive).\n\nIf 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.\n\nField names cannot begin by '$' or contain a '.'.\n\n```javascript\nvar doc = { hello: 'world'\n               , n: 5\n               , today: new Date()\n               , nedbIsAwesome: true\n               , notthere: null\n               , notToBeSaved: undefined  \u002F\u002F Will not be saved\n               , fruits: [ 'apple', 'orange', 'pear' ]\n               , infos: { name: 'nedb' }\n               };\n\ndb.insert(doc, function (err, newDoc) {   \u002F\u002F Callback is optional\n  \u002F\u002F newDoc is the newly inserted document, including its _id\n  \u002F\u002F newDoc has no key called notToBeSaved since its value was undefined\n});\n```\n\nYou 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.\n\n```javascript\ndb.insert([{ a: 5 }, { a: 42 }], function (err, newDocs) {\n  \u002F\u002F Two documents were inserted in the database\n  \u002F\u002F newDocs is an array with these documents, augmented with their _id\n});\n\n\u002F\u002F If there is a unique constraint on field 'a', this will fail\ndb.insert([{ a: 5 }, { a: 42 }, { a: 5 }], function (err) {\n  \u002F\u002F err is a 'uniqueViolated' error\n  \u002F\u002F The database was not modified\n});\n```\n\n### Finding documents\nUse `find` to look for multiple documents matching you query, or `findOne` to look for one specific document. You can select documents based on field equality or use comparison operators (`$lt`, `$lte`, `$gt`, `$gte`, `$in`, `$nin`, `$ne`). You can also use logical operators `$or`, `$and`, `$not` and `$where`. See below for the syntax.\n\nYou can use regular expressions in two ways: in basic querying in place of a string, or with the `$regex` operator.\n\nYou can sort and paginate results using the cursor API (see below).\n\nYou can use standard projections to restrict the fields to appear in the results (see below).\n\n#### Basic querying\nBasic querying means are looking for documents whose fields match the ones you specify. You can use regular expression to match strings.\nYou can use the dot notation to navigate inside nested documents, arrays, arrays of subdocuments and to match a specific element of an array.\n\n```javascript\n\u002F\u002F Let's say our datastore contains the following collection\n\u002F\u002F { _id: 'id1', planet: 'Mars', system: 'solar', inhabited: false, satellites: ['Phobos', 'Deimos'] }\n\u002F\u002F { _id: 'id2', planet: 'Earth', system: 'solar', inhabited: true, humans: { genders: 2, eyes: true } }\n\u002F\u002F { _id: 'id3', planet: 'Jupiter', system: 'solar', inhabited: false }\n\u002F\u002F { _id: 'id4', planet: 'Omicron Persei 8', system: 'futurama', inhabited: true, humans: { genders: 7 } }\n\u002F\u002F { _id: 'id5', completeData: { planets: [ { name: 'Earth', number: 3 }, { name: 'Mars', number: 2 }, { name: 'Pluton', number: 9 } ] } }\n\n\u002F\u002F Finding all planets in the solar system\ndb.find({ system: 'solar' }, function (err, docs) {\n  \u002F\u002F docs is an array containing documents Mars, Earth, Jupiter\n  \u002F\u002F If no document is found, docs is equal to []\n});\n\n\u002F\u002F Finding all planets whose name contain the substring 'ar' using a regular expression\ndb.find({ planet: \u002Far\u002F }, function (err, docs) {\n  \u002F\u002F docs contains Mars and Earth\n});\n\n\u002F\u002F Finding all inhabited planets in the solar system\ndb.find({ system: 'solar', inhabited: true }, function (err, docs) {\n  \u002F\u002F docs is an array containing document Earth only\n});\n\n\u002F\u002F Use the dot-notation to match fields in subdocuments\ndb.find({ \"humans.genders\": 2 }, function (err, docs) {\n  \u002F\u002F docs contains Earth\n});\n\n\u002F\u002F Use the dot-notation to navigate arrays of subdocuments\ndb.find({ \"completeData.planets.name\": \"Mars\" }, function (err, docs) {\n  \u002F\u002F docs contains document 5\n});\n\ndb.find({ \"completeData.planets.name\": \"Jupiter\" }, function (err, docs) {\n  \u002F\u002F docs is empty\n});\n\ndb.find({ \"completeData.planets.0.name\": \"Earth\" }, function (err, docs) {\n  \u002F\u002F docs contains document 5\n  \u002F\u002F If we had tested against \"Mars\" docs would be empty because we are matching against a specific array element\n});\n\n\n\u002F\u002F You can also deep-compare objects. Don't confuse this with dot-notation!\ndb.find({ humans: { genders: 2 } }, function (err, docs) {\n  \u002F\u002F docs is empty, because { genders: 2 } is not equal to { genders: 2, eyes: true }\n});\n\n\u002F\u002F Find all documents in the collection\ndb.find({}, function (err, docs) {\n});\n\n\u002F\u002F The same rules apply when you want to only find one document\ndb.findOne({ _id: 'id1' }, function (err, doc) {\n  \u002F\u002F doc is the document Mars\n  \u002F\u002F If no document is found, doc is null\n});\n```\n\n#### Operators ($lt, $lte, $gt, $gte, $in, $nin, $ne, $exists, $regex)\nThe syntax is `{ field: { $op: value } }` where `$op` is any comparison operator:  \n\n* `$lt`, `$lte`: less than, less than or equal\n* `$gt`, `$gte`: greater than, greater than or equal\n* `$in`: member of. `value` must be an array of values\n* `$ne`, `$nin`: not equal, not a member of\n* `$exists`: checks whether the document posses the property `field`. `value` should be true or false\n* `$regex`: checks whether a string is matched by the regular expression. Contrary to MongoDB, the use of `$options` with `$regex` is not supported, because it doesn't give you more power than regex flags. Basic queries are more readable so only use the `$regex` operator when you need to use another operator with it (see example below)\n\n```javascript\n\u002F\u002F $lt, $lte, $gt and $gte work on numbers and strings\ndb.find({ \"humans.genders\": { $gt: 5 } }, function (err, docs) {\n  \u002F\u002F docs contains Omicron Persei 8, whose humans have more than 5 genders (7).\n});\n\n\u002F\u002F When used with strings, lexicographical order is used\ndb.find({ planet: { $gt: 'Mercury' }}, function (err, docs) {\n  \u002F\u002F docs contains Omicron Persei 8\n})\n\n\u002F\u002F Using $in. $nin is used in the same way\ndb.find({ planet: { $in: ['Earth', 'Jupiter'] }}, function (err, docs) {\n  \u002F\u002F docs contains Earth and Jupiter\n});\n\n\u002F\u002F Using $exists\ndb.find({ satellites: { $exists: true } }, function (err, docs) {\n  \u002F\u002F docs contains only Mars\n});\n\n\u002F\u002F Using $regex with another operator\ndb.find({ planet: { $regex: \u002Far\u002F, $nin: ['Jupiter', 'Earth'] } }, function (err, docs) {\n  \u002F\u002F docs only contains Mars because Earth was excluded from the match by $nin\n});\n```\n\n#### Array fields\nWhen a field in a document is an array, NeDB first tries to see if the query value is an array to perform an exact match, then whether there is an array-specific comparison function (for now there is only `$size` and `$elemMatch`) being used. If not, the query is treated as a query on every element and there is a match if at least one element matches.  \n\n* `$size`: match on the size of the array\n* `$elemMatch`: matches if at least one array element matches the query entirely\n\n```javascript\n\u002F\u002F Exact match\ndb.find({ satellites: ['Phobos', 'Deimos'] }, function (err, docs) {\n  \u002F\u002F docs contains Mars\n})\ndb.find({ satellites: ['Deimos', 'Phobos'] }, function (err, docs) {\n  \u002F\u002F docs is empty\n})\n\n\u002F\u002F Using an array-specific comparison function\n\u002F\u002F $elemMatch operator will provide match for a document, if an element from the array field satisfies all the conditions specified with the `$elemMatch` operator\ndb.find({ completeData: { planets: { $elemMatch: { name: 'Earth', number: 3 } } } }, function (err, docs) {\n  \u002F\u002F docs contains documents with id 5 (completeData)\n});\n\ndb.find({ completeData: { planets: { $elemMatch: { name: 'Earth', number: 5 } } } }, function (err, docs) {\n  \u002F\u002F docs is empty\n});\n\n\u002F\u002F You can use inside #elemMatch query any known document query operator\ndb.find({ completeData: { planets: { $elemMatch: { name: 'Earth', number: { $gt: 2 } } } } }, function (err, docs) {\n  \u002F\u002F docs contains documents with id 5 (completeData)\n});\n\n\u002F\u002F Note: you can't use nested comparison functions, e.g. { $size: { $lt: 5 } } will throw an error\ndb.find({ satellites: { $size: 2 } }, function (err, docs) {\n  \u002F\u002F docs contains Mars\n});\n\ndb.find({ satellites: { $size: 1 } }, function (err, docs) {\n  \u002F\u002F docs is empty\n});\n\n\u002F\u002F If a document's field is an array, matching it means matching any element of the array\ndb.find({ satellites: 'Phobos' }, function (err, docs) {\n  \u002F\u002F docs contains Mars. Result would have been the same if query had been { satellites: 'Deimos' }\n});\n\n\u002F\u002F This also works for queries that use comparison operators\ndb.find({ satellites: { $lt: 'Amos' } }, function (err, docs) {\n  \u002F\u002F docs is empty since Phobos and Deimos are after Amos in lexicographical order\n});\n\n\u002F\u002F This also works with the $in and $nin operator\ndb.find({ satellites: { $in: ['Moon', 'Deimos'] } }, function (err, docs) {\n  \u002F\u002F docs contains Mars (the Earth document is not complete!)\n});\n```\n\n#### Logical operators $or, $and, $not, $where\nYou can combine queries using logical operators:  \n\n* For `$or` and `$and`, the syntax is `{ $op: [query1, query2, ...] }`.\n* For `$not`, the syntax is `{ $not: query }`\n* For `$where`, the syntax is `{ $where: function () { \u002F* object is \"this\", return a boolean *\u002F } }`\n\n```javascript\ndb.find({ $or: [{ planet: 'Earth' }, { planet: 'Mars' }] }, function (err, docs) {\n  \u002F\u002F docs contains Earth and Mars\n});\n\ndb.find({ $not: { planet: 'Earth' } }, function (err, docs) {\n  \u002F\u002F docs contains Mars, Jupiter, Omicron Persei 8\n});\n\ndb.find({ $where: function () { return Object.keys(this) > 6; } }, function (err, docs) {\n  \u002F\u002F docs with more than 6 properties\n});\n\n\u002F\u002F You can mix normal queries, comparison queries and logical operators\ndb.find({ $or: [{ planet: 'Earth' }, { planet: 'Mars' }], inhabited: true }, function (err, docs) {\n  \u002F\u002F docs contains Earth\n});\n\n```\n\n#### Sorting and paginating\nIf you don't specify a callback to `find`, `findOne` or `count`, a `Cursor` object is returned. You can modify the cursor with `sort`, `skip` and `limit` and then execute it with `exec(callback)`.\n\n```javascript\n\u002F\u002F Let's say the database contains these 4 documents\n\u002F\u002F doc1 = { _id: 'id1', planet: 'Mars', system: 'solar', inhabited: false, satellites: ['Phobos', 'Deimos'] }\n\u002F\u002F doc2 = { _id: 'id2', planet: 'Earth', system: 'solar', inhabited: true, humans: { genders: 2, eyes: true } }\n\u002F\u002F doc3 = { _id: 'id3', planet: 'Jupiter', system: 'solar', inhabited: false }\n\u002F\u002F doc4 = { _id: 'id4', planet: 'Omicron Persei 8', system: 'futurama', inhabited: true, humans: { genders: 7 } }\n\n\u002F\u002F No query used means all results are returned (before the Cursor modifiers)\ndb.find({}).sort({ planet: 1 }).skip(1).limit(2).exec(function (err, docs) {\n  \u002F\u002F docs is [doc3, doc1]\n});\n\n\u002F\u002F You can sort in reverse order like this\ndb.find({ system: 'solar' }).sort({ planet: -1 }).exec(function (err, docs) {\n  \u002F\u002F docs is [doc1, doc3, doc2]\n});\n\n\u002F\u002F You can sort on one field, then another, and so on like this:\ndb.find({}).sort({ firstField: 1, secondField: -1 }) ...   \u002F\u002F You understand how this works!\n```\n\n#### Projections\nYou can give `find` and `findOne` an optional second argument, `projections`. The syntax is the same as MongoDB: `{ a: 1, b: 1 }` to return only the `a` and `b` fields, `{ a: 0, b: 0 }` to omit these two fields. You cannot use both modes at the time, except for `_id` which is by default always returned and which you can choose to omit. You can project on nested documents.\n\n```javascript\n\u002F\u002F Same database as above\n\n\u002F\u002F Keeping only the given fields\ndb.find({ planet: 'Mars' }, { planet: 1, system: 1 }, function (err, docs) {\n  \u002F\u002F docs is [{ planet: 'Mars', system: 'solar', _id: 'id1' }]\n});\n\n\u002F\u002F Keeping only the given fields but removing _id\ndb.find({ planet: 'Mars' }, { planet: 1, system: 1, _id: 0 }, function (err, docs) {\n  \u002F\u002F docs is [{ planet: 'Mars', system: 'solar' }]\n});\n\n\u002F\u002F Omitting only the given fields and removing _id\ndb.find({ planet: 'Mars' }, { planet: 0, system: 0, _id: 0 }, function (err, docs) {\n  \u002F\u002F docs is [{ inhabited: false, satellites: ['Phobos', 'Deimos'] }]\n});\n\n\u002F\u002F Failure: using both modes at the same time\ndb.find({ planet: 'Mars' }, { planet: 0, system: 1 }, function (err, docs) {\n  \u002F\u002F err is the error message, docs is undefined\n});\n\n\u002F\u002F You can also use it in a Cursor way but this syntax is not compatible with MongoDB\ndb.find({ planet: 'Mars' }).projection({ planet: 1, system: 1 }).exec(function (err, docs) {\n  \u002F\u002F docs is [{ planet: 'Mars', system: 'solar', _id: 'id1' }]\n});\n\n\u002F\u002F Project on a nested document\ndb.findOne({ planet: 'Earth' }).projection({ planet: 1, 'humans.genders': 1 }).exec(function (err, doc) {\n  \u002F\u002F doc is { planet: 'Earth', _id: 'id2', humans: { genders: 2 } }\n});\n```\n\n\n\n### Counting documents\nYou can use `count` to count documents. It has the same syntax as `find`. For example:\n\n```javascript\n\u002F\u002F Count all planets in the solar system\ndb.count({ system: 'solar' }, function (err, count) {\n  \u002F\u002F count equals to 3\n});\n\n\u002F\u002F Count all documents in the datastore\ndb.count({}, function (err, count) {\n  \u002F\u002F count equals to 4\n});\n```\n\n\n### Updating documents\n`db.update(query, update, options, callback)` will update all documents matching `query` according to the `update` rules:  \n* `query` is the same kind of finding query you use with `find` and `findOne`\n* `update` specifies how the documents should be modified. It is either a new document or a set of modifiers (you cannot use both together, it doesn't make sense!)\n  * A new document will replace the matched docs\n  * The modifiers create the fields they need to modify if they don't exist, and you can apply them to subdocs. Available field modifiers are `$set` to change a field's value, `$unset` to delete a field, `$inc` to increment a field's value and `$min`\u002F`$max` to change field's value, only if provided value is less\u002Fgreater than current value. To work on arrays, you have `$push`, `$pop`, `$addToSet`, `$pull`, and the special `$each` and `$slice`. See examples below for the syntax.\n* `options` is an object with two possible parameters\n  * `multi` (defaults to `false`) which allows the modification of several documents if set to true\n  * `upsert` (defaults to `false`) if you want to insert a new document corresponding to the `update` rules if your `query` doesn't match anything. If your `update` is a simple object with no modifiers, it is the inserted document. In the other case, the `query` is stripped from all operator recursively, and the `update` is applied to it.\n  * `returnUpdatedDocs` (defaults to `false`, not MongoDB-compatible) if set to true and update is not an upsert, will return the array of documents matched by the find query and updated. Updated documents will be returned even if the update did not actually modify them.\n* `callback` (optional) signature: `(err, numAffected, affectedDocuments, upsert)`. **Warning**: the API was changed between v1.7.4 and v1.8. Please refer to the \u003Ca href=\"https:\u002F\u002Fgithub.com\u002Flouischatriot\u002Fnedb\u002Fwiki\u002FChange-log\" target=\"_blank\">change log\u003C\u002Fa> to see the change.\n  * For an upsert, `affectedDocuments` contains the inserted document and the `upsert` flag is set to `true`.\n  * For a standard update with `returnUpdatedDocs` flag set to `false`, `affectedDocuments` is not set.\n  * For a standard update with `returnUpdatedDocs` flag set to `true` and `multi` to `false`, `affectedDocuments` is the updated document.\n  * For a standard update with `returnUpdatedDocs` flag set to `true` and `multi` to `true`, `affectedDocuments` is the array of updated documents.\n\n**Note**: you can't change a document's _id.\n\n```javascript\n\u002F\u002F Let's use the same example collection as in the \"finding document\" part\n\u002F\u002F { _id: 'id1', planet: 'Mars', system: 'solar', inhabited: false }\n\u002F\u002F { _id: 'id2', planet: 'Earth', system: 'solar', inhabited: true }\n\u002F\u002F { _id: 'id3', planet: 'Jupiter', system: 'solar', inhabited: false }\n\u002F\u002F { _id: 'id4', planet: 'Omicron Persia 8', system: 'futurama', inhabited: true }\n\n\u002F\u002F Replace a document by another\ndb.update({ planet: 'Jupiter' }, { planet: 'Pluton'}, {}, function (err, numReplaced) {\n  \u002F\u002F numReplaced = 1\n  \u002F\u002F The doc #3 has been replaced by { _id: 'id3', planet: 'Pluton' }\n  \u002F\u002F Note that the _id is kept unchanged, and the document has been replaced\n  \u002F\u002F (the 'system' and inhabited fields are not here anymore)\n});\n\n\u002F\u002F Set an existing field's value\ndb.update({ system: 'solar' }, { $set: { system: 'solar system' } }, { multi: true }, function (err, numReplaced) {\n  \u002F\u002F numReplaced = 3\n  \u002F\u002F Field 'system' on Mars, Earth, Jupiter now has value 'solar system'\n});\n\n\u002F\u002F Setting the value of a non-existing field in a subdocument by using the dot-notation\ndb.update({ planet: 'Mars' }, { $set: { \"data.satellites\": 2, \"data.red\": true } }, {}, function () {\n  \u002F\u002F Mars document now is { _id: 'id1', system: 'solar', inhabited: false\n  \u002F\u002F                      , data: { satellites: 2, red: true }\n  \u002F\u002F                      }\n  \u002F\u002F Not that to set fields in subdocuments, you HAVE to use dot-notation\n  \u002F\u002F Using object-notation will just replace the top-level field\n  db.update({ planet: 'Mars' }, { $set: { data: { satellites: 3 } } }, {}, function () {\n    \u002F\u002F Mars document now is { _id: 'id1', system: 'solar', inhabited: false\n    \u002F\u002F                      , data: { satellites: 3 }\n    \u002F\u002F                      }\n    \u002F\u002F You lost the \"data.red\" field which is probably not the intended behavior\n  });\n});\n\n\u002F\u002F Deleting a field\ndb.update({ planet: 'Mars' }, { $unset: { planet: true } }, {}, function () {\n  \u002F\u002F Now the document for Mars doesn't contain the planet field\n  \u002F\u002F You can unset nested fields with the dot notation of course\n});\n\n\u002F\u002F Upserting a document\ndb.update({ planet: 'Pluton' }, { planet: 'Pluton', inhabited: false }, { upsert: true }, function (err, numReplaced, upsert) {\n  \u002F\u002F numReplaced = 1, upsert = { _id: 'id5', planet: 'Pluton', inhabited: false }\n  \u002F\u002F A new document { _id: 'id5', planet: 'Pluton', inhabited: false } has been added to the collection\n});\n\n\u002F\u002F If you upsert with a modifier, the upserted doc is the query modified by the modifier\n\u002F\u002F This is simpler than it sounds :)\ndb.update({ planet: 'Pluton' }, { $inc: { distance: 38 } }, { upsert: true }, function () {\n  \u002F\u002F A new document { _id: 'id5', planet: 'Pluton', distance: 38 } has been added to the collection  \n});\n\n\u002F\u002F If we insert a new document { _id: 'id6', fruits: ['apple', 'orange', 'pear'] } in the collection,\n\u002F\u002F let's see how we can modify the array field atomically\n\n\u002F\u002F $push inserts new elements at the end of the array\ndb.update({ _id: 'id6' }, { $push: { fruits: 'banana' } }, {}, function () {\n  \u002F\u002F Now the fruits array is ['apple', 'orange', 'pear', 'banana']\n});\n\n\u002F\u002F $pop removes an element from the end (if used with 1) or the front (if used with -1) of the array\ndb.update({ _id: 'id6' }, { $pop: { fruits: 1 } }, {}, function () {\n  \u002F\u002F Now the fruits array is ['apple', 'orange']\n  \u002F\u002F With { $pop: { fruits: -1 } }, it would have been ['orange', 'pear']\n});\n\n\u002F\u002F $addToSet adds an element to an array only if it isn't already in it\n\u002F\u002F Equality is deep-checked (i.e. $addToSet will not insert an object in an array already containing the same object)\n\u002F\u002F Note that it doesn't check whether the array contained duplicates before or not\ndb.update({ _id: 'id6' }, { $addToSet: { fruits: 'apple' } }, {}, function () {\n  \u002F\u002F The fruits array didn't change\n  \u002F\u002F If we had used a fruit not in the array, e.g. 'banana', it would have been added to the array\n});\n\n\u002F\u002F $pull removes all values matching a value or even any NeDB query from the array\ndb.update({ _id: 'id6' }, { $pull: { fruits: 'apple' } }, {}, function () {\n  \u002F\u002F Now the fruits array is ['orange', 'pear']\n});\ndb.update({ _id: 'id6' }, { $pull: { fruits: $in: ['apple', 'pear'] } }, {}, function () {\n  \u002F\u002F Now the fruits array is ['orange']\n});\n\n\u002F\u002F $each can be used to $push or $addToSet multiple values at once\n\u002F\u002F This example works the same way with $addToSet\ndb.update({ _id: 'id6' }, { $push: { fruits: { $each: ['banana', 'orange'] } } }, {}, function () {\n  \u002F\u002F Now the fruits array is ['apple', 'orange', 'pear', 'banana', 'orange']\n});\n\n\u002F\u002F $slice can be used in cunjunction with $push and $each to limit the size of the resulting array.\n\u002F\u002F A value of 0 will update the array to an empty array. A positive value n will keep only the n first elements\n\u002F\u002F A negative value -n will keep only the last n elements.\n\u002F\u002F If $slice is specified but not $each, $each is set to []\ndb.update({ _id: 'id6' }, { $push: { fruits: { $each: ['banana'], $slice: 2 } } }, {}, function () {\n  \u002F\u002F Now the fruits array is ['apple', 'orange']\n});\n\n\u002F\u002F $min\u002F$max to update only if provided value is less\u002Fgreater than current value\n\u002F\u002F Let's say the database contains this document\n\u002F\u002F doc = { _id: 'id', name: 'Name', value: 5 }\ndb.update({ _id: 'id1' }, { $min: { value: 2 } }, {}, function () {\n  \u002F\u002F The document will be updated to { _id: 'id', name: 'Name', value: 2 }\n});\n\ndb.update({ _id: 'id1' }, { $min: { value: 8 } }, {}, function () {\n  \u002F\u002F The document will not be modified\n});\n```\n\n### Removing documents\n`db.remove(query, options, callback)` will remove all documents matching `query` according to `options`  \n* `query` is the same as the ones used for finding and updating\n* `options` only one option for now: `multi` which allows the removal of multiple documents if set to true. Default is false\n* `callback` is optional, signature: err, numRemoved\n\n```javascript\n\u002F\u002F Let's use the same example collection as in the \"finding document\" part\n\u002F\u002F { _id: 'id1', planet: 'Mars', system: 'solar', inhabited: false }\n\u002F\u002F { _id: 'id2', planet: 'Earth', system: 'solar', inhabited: true }\n\u002F\u002F { _id: 'id3', planet: 'Jupiter', system: 'solar', inhabited: false }\n\u002F\u002F { _id: 'id4', planet: 'Omicron Persia 8', system: 'futurama', inhabited: true }\n\n\u002F\u002F Remove one document from the collection\n\u002F\u002F options set to {} since the default for multi is false\ndb.remove({ _id: 'id2' }, {}, function (err, numRemoved) {\n  \u002F\u002F numRemoved = 1\n});\n\n\u002F\u002F Remove multiple documents\ndb.remove({ system: 'solar' }, { multi: true }, function (err, numRemoved) {\n  \u002F\u002F numRemoved = 3\n  \u002F\u002F All planets from the solar system were removed\n});\n\n\u002F\u002F Removing all documents with the 'match-all' query\ndb.remove({}, { multi: true }, function (err, numRemoved) {\n});\n```\n\n### Indexing\nNeDB supports indexing. It gives a very nice speed boost and can be used to enforce a unique constraint on a field. You can index any field, including fields in nested documents using the dot notation. For now, indexes are only used to speed up basic queries and queries using `$in`, `$lt`, `$lte`, `$gt` and `$gte`. The indexed values cannot be of type array of object.\n\nTo create an index, use `datastore.ensureIndex(options, cb)`, where callback is optional and get passed an error if any (usually a unique constraint that was violated). `ensureIndex` can be called when you want, even after some data was inserted, though it's best to call it at application startup. The options are:  \n\n* **fieldName** (required): name of the field to index. Use the dot notation to index a field in a nested document.\n* **unique** (optional, defaults to `false`): enforce field uniqueness. Note that a unique index will raise an error if you try to index two documents for which the field is not defined.\n* **sparse** (optional, defaults to `false`): don't index documents for which the field is not defined. Use this option along with \"unique\" if you want to accept multiple documents for which it is not defined.\n* **expireAfterSeconds** (number of seconds, optional): if set, the created index is a TTL (time to live) index, that will automatically remove documents when the system date becomes larger than the date on the indexed field plus `expireAfterSeconds`. Documents where the indexed field is not specified or not a `Date` object are ignored\n\nNote: the `_id` is automatically indexed with a unique constraint, no need to call `ensureIndex` on it.\n\nYou can remove a previously created index with `datastore.removeIndex(fieldName, cb)`.\n\nIf your datastore is persistent, the indexes you created are persisted in the datafile, when you load the database a second time they are automatically created for you. No need to remove any `ensureIndex` though, if it is called on a database that already has the index, nothing happens.\n\n```javascript\ndb.ensureIndex({ fieldName: 'somefield' }, function (err) {\n  \u002F\u002F If there was an error, err is not null\n});\n\n\u002F\u002F Using a unique constraint with the index\ndb.ensureIndex({ fieldName: 'somefield', unique: true }, function (err) {\n});\n\n\u002F\u002F Using a sparse unique index\ndb.ensureIndex({ fieldName: 'somefield', unique: true, sparse: true }, function (err) {\n});\n\n\n\u002F\u002F Format of the error message when the unique constraint is not met\ndb.insert({ somefield: 'nedb' }, function (err) {\n  \u002F\u002F err is null\n  db.insert({ somefield: 'nedb' }, function (err) {\n    \u002F\u002F err is { errorType: 'uniqueViolated'\n    \u002F\u002F        , key: 'name'\n    \u002F\u002F        , message: 'Unique constraint violated for key name' }\n  });\n});\n\n\u002F\u002F Remove index on field somefield\ndb.removeIndex('somefield', function (err) {\n});\n\n\u002F\u002F Example of using expireAfterSeconds to remove documents 1 hour\n\u002F\u002F after their creation (db's timestampData option is true here)\ndb.ensureIndex({ fieldName: 'createdAt', expireAfterSeconds: 3600 }, function (err) {\n});\n\n\u002F\u002F You can also use the option to set an expiration date like so\ndb.ensureIndex({ fieldName: 'expirationDate', expireAfterSeconds: 0 }, function (err) {\n  \u002F\u002F Now all documents will expire when system time reaches the date in their\n  \u002F\u002F expirationDate field\n});\n\n```\n\n**Note:** the `ensureIndex` function creates the index synchronously, so it's best to use it at application startup. It's quite fast so it doesn't increase startup time much (35 ms for a collection containing 10,000 documents).\n\n\n## Browser version\nThe browser version and its minified counterpart are in the `browser-version\u002Fout` directory. You only need to require `nedb.js` or `nedb.min.js` in your HTML file and the global object `Nedb` can be used right away, with the same API as the server version:\n\n```\n\u003Cscript src=\"nedb.min.js\">\u003C\u002Fscript>\n\u003Cscript>\n  var db = new Nedb();   \u002F\u002F Create an in-memory only datastore\n  \n  db.insert({ planet: 'Earth' }, function (err) {\n   db.find({}, function (err, docs) {\n     \u002F\u002F docs contains the two planets Earth and Mars\n   });\n  });\n\u003C\u002Fscript>\n```\n\nIf you specify a `filename`, the database will be persistent, and automatically select the best storage method available (IndexedDB, WebSQL or localStorage) depending on the browser. In most cases that means a lot of data can be stored, typically in hundreds of MB. **WARNING**: the storage system changed between v1.3 and v1.4 and is NOT back-compatible! Your application needs to resync client-side when you upgrade NeDB.\n\nNeDB is compatible with all major browsers: Chrome, Safari, Firefox, IE9+. Tests are in the `browser-version\u002Ftest` directory (files `index.html` and `testPersistence.html`).\n\nIf you fork and modify nedb, you can build the browser version from the sources, the build script is `browser-version\u002Fbuild.js`.\n\n\n## Performance\n### Speed\nNeDB is not intended to be a replacement of large-scale databases such as MongoDB, and as such was not designed for speed. That said, it is still pretty fast on the expected datasets, especially if you use indexing. On a typical, not-so-fast dev machine, for a collection containing 10,000 documents, with indexing:  \n* Insert: **10,680 ops\u002Fs**\n* Find: **43,290 ops\u002Fs**\n* Update: **8,000 ops\u002Fs**\n* Remove: **11,750 ops\u002Fs**  \n\nYou can run these simple benchmarks by executing the scripts in the `benchmarks` folder. Run them with the `--help` flag to see how they work.\n\n### Memory footprint\nA copy of the whole database is kept in memory. This is not much on the\nexpected kind of datasets (20MB for 10,000 2KB documents).\n\n## Use in other services\n* \u003Ca href=\"https:\u002F\u002Fgithub.com\u002Flouischatriot\u002Fconnect-nedb-session\"\n  target=\"_blank\">connect-nedb-session\u003C\u002Fa> is a session store for\nConnect and Express, backed by nedb\n* If you mostly use NeDB for logging purposes and don't want the memory footprint of your application to grow too large, you can use \u003Ca href=\"https:\u002F\u002Fgithub.com\u002Flouischatriot\u002Fnedb-logger\" target=\"_blank\">NeDB Logger\u003C\u002Fa> to insert documents in a NeDB-readable database\n* If you've outgrown NeDB, switching to MongoDB won't be too hard as it is the same API. Use \u003Ca href=\"https:\u002F\u002Fgithub.com\u002Flouischatriot\u002Fnedb-to-mongodb\" target=\"_blank\">this utility\u003C\u002Fa> to transfer the data from a NeDB database to a MongoDB collection\n* An ODM for NeDB: \u003Ca href=\"https:\u002F\u002Fgithub.com\u002Fscottwrobinson\u002Fcamo\" target=\"_blank\">Camo\u003C\u002Fa>\n\n## Pull requests\n**Important: I consider NeDB to be feature-complete, i.e. it does everything I think it should and nothing more. As a general rule I will not accept pull requests anymore, except for bugfixes (of course) or if I get convinced I overlook a strong usecase. Please make sure to open an issue before spending time on any PR.**\n\nIf you submit a pull request, thanks! There are a couple rules to follow though to make it manageable:\n* The pull request should be atomic, i.e. contain only one feature. If it contains more, please submit multiple pull requests. Reviewing massive, 1000 loc+ pull requests is extremely hard.\n* Likewise, if for one unique feature the pull request grows too large (more than 200 loc tests not included), please get in touch first.\n* Please stick to the current coding style. It's important that the code uses a coherent style for readability.\n* Do not include sylistic improvements (\"housekeeping\"). If you think one part deserves lots of housekeeping, use a separate pull request so as not to pollute the code.\n* Don't forget tests for your new feature. Also don't forget to run the whole test suite before submitting to make sure you didn't introduce regressions.\n* Do not build the browser version in your branch, I'll take care of it once the code is merged.\n* Update the readme accordingly.\n* Last but not least: keep in mind what NeDB's mindset is! The goal is not to be a replacement for MongoDB, but to have a pure JS database, easy to use, cross platform, fast and expressive enough for the target projects (small and self contained apps on server\u002Fdesktop\u002Fbrowser\u002Fmobile). Sometimes it's better to shoot for simplicity than for API completeness with regards to MongoDB.\n\n## Bug reporting guidelines\nIf you report a bug, thank you! That said for the process to be manageable please strictly adhere to the following guidelines. I'll not be able to handle bug reports that don't:\n* Your bug report should be a self-containing gist complete with a package.json for any dependencies you need. I need to run through a simple `git clone gist; npm install; node bugreport.js`, nothing more.\n* It should use assertions to showcase the expected vs actual behavior and be hysteresis-proof. It's quite simple in fact, see this example: https:\u002F\u002Fgist.github.com\u002Flouischatriot\u002F220cf6bd29c7de06a486\n* Simplify as much as you can. Strip all your application-specific code. Most of the time you will see that there is no bug but an error in your code :)\n* 50 lines max. If you need more, read the above point and rework your bug report. If you're **really** convinced you need more, please explain precisely in the issue.\n* The code should be Javascript, not Coffeescript.\n\n### Bitcoins\nYou don't have time? You can support NeDB by sending bitcoins to this address: 1dDZLnWpBbodPiN8sizzYrgaz5iahFyb1\n\n\n## License \n\nSee [License](LICENSE)\n","NeDB 是一个适用于 Node.js、nw.js、Electron 和浏览器的 JavaScript 数据库。它提供了一个嵌入式的持久化或内存数据库，完全基于 JavaScript，无需任何二进制依赖。其 API 设计参考了 MongoDB 的一部分常用操作，支持基本的文档插入、查询、更新和删除等功能，并且可以在多种环境中轻松集成。尽管该项目已不再维护，但 NeDB 仍然适合需要轻量级数据库解决方案的小型应用或开发项目中使用。","2026-06-11 02:53:58","top_language"]