or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

cursor-operations.mddatabase-management.mddocument-operations.mdindex-management.mdindex.mdquery-system.md

database-management.mddocs/

0

# Database Management

1

2

Core database initialization, loading, and lifecycle management including persistence configuration and compaction operations.

3

4

## Capabilities

5

6

### Database Constructor

7

8

Creates a new NeDB database instance with configurable persistence, indexing, and data processing options.

9

10

```javascript { .api }

11

/**

12

* Creates a new NeDB database instance

13

* @param {string|object} options - Database configuration or filename (legacy)

14

*/

15

constructor Datastore(options);

16

17

/**

18

* Constructor options for database configuration

19

*/

20

interface DatastoreOptions {

21

filename?: string; // Path to database file (null for in-memory)

22

inMemoryOnly?: boolean; // Force memory-only storage (default: false)

23

autoload?: boolean; // Automatically load database on creation (default: false)

24

timestampData?: boolean; // Add createdAt/updatedAt timestamps (default: false)

25

onload?: (err: Error) => void; // Callback executed after autoload

26

afterSerialization?: (data: string) => string; // Transform data before disk write

27

beforeDeserialization?: (data: string) => string; // Transform data after disk read

28

corruptAlertThreshold?: number; // Corruption tolerance threshold 0-1 (default: 0.1)

29

compareStrings?: (a: string, b: string) => number; // Custom string comparison function

30

nodeWebkitAppName?: string; // NW.js app name for relative paths (deprecated)

31

}

32

```

33

34

**Usage Examples:**

35

36

```javascript

37

const Datastore = require('nedb');

38

39

// In-memory database

40

const memoryDb = new Datastore();

41

42

// Persistent database with autoload

43

const db = new Datastore({

44

filename: './data/users.db',

45

autoload: true

46

});

47

48

// Database with timestamps and custom serialization

49

const timestampDb = new Datastore({

50

filename: './data/logs.db',

51

timestampData: true,

52

afterSerialization: (data) => {

53

// Compress data before writing

54

return compress(data);

55

},

56

beforeDeserialization: (data) => {

57

// Decompress data after reading

58

return decompress(data);

59

}

60

});

61

62

// Legacy constructor (v0.6 compatibility)

63

const legacyDb = new Datastore('./data/legacy.db');

64

```

65

66

### Database Loading

67

68

Explicitly load database from persistent storage, triggering execution of any buffered commands.

69

70

```javascript { .api }

71

/**

72

* Load database from datafile and execute buffered commands

73

* @param {function} callback - Optional callback function (err) => {}

74

*/

75

loadDatabase(callback);

76

```

77

78

**Usage Examples:**

79

80

```javascript

81

const db = new Datastore({ filename: './data.db' });

82

83

// Load database with callback

84

db.loadDatabase((err) => {

85

if (err) {

86

console.error('Failed to load database:', err);

87

return;

88

}

89

console.log('Database loaded successfully');

90

91

// Database is now ready for operations

92

db.insert({ message: 'Hello World' }, (err, doc) => {

93

if (!err) console.log('Document inserted:', doc);

94

});

95

});

96

97

// Load database without callback (errors will be thrown)

98

db.loadDatabase();

99

```

100

101

### Database Properties

102

103

Access database configuration and internal state through instance properties.

104

105

```javascript { .api }

106

/**

107

* Database instance properties

108

*/

109

interface DatastoreProperties {

110

filename: string | null; // Database file path (null for in-memory)

111

inMemoryOnly: boolean; // Memory-only storage flag

112

autoload: boolean; // Autoload configuration flag

113

timestampData: boolean; // Timestamp configuration flag

114

compareStrings: function; // Custom string comparison function

115

persistence: Persistence; // Persistence handler instance

116

executor: Executor; // Command executor instance

117

indexes: object; // Field name to Index mapping

118

ttlIndexes: object; // TTL index configurations

119

}

120

```

121

122

**Usage Examples:**

123

124

```javascript

125

const db = new Datastore({

126

filename: './data.db',

127

timestampData: true

128

});

129

130

console.log('Database file:', db.filename); // './data.db'

131

console.log('In memory only:', db.inMemoryOnly); // false

132

console.log('Timestamps enabled:', db.timestampData); // true

133

console.log('Available indexes:', Object.keys(db.indexes)); // ['_id', ...]

134

```

135

136

### Database Compaction

137

138

Manual and automatic database compaction to optimize storage and remove deleted documents.

139

140

```javascript { .api }

141

/**

142

* Manually trigger database compaction

143

*/

144

persistence.compactDatafile();

145

146

/**

147

* Set automatic compaction interval

148

* @param {number} interval - Milliseconds between compactions (minimum 5000)

149

*/

150

persistence.setAutocompactionInterval(interval);

151

152

/**

153

* Stop automatic compaction

154

*/

155

persistence.stopAutocompaction();

156

```

157

158

**Usage Examples:**

159

160

```javascript

161

const db = new Datastore({ filename: './data.db', autoload: true });

162

163

// Manual compaction

164

db.persistence.compactDatafile();

165

166

// Automatic compaction every 30 seconds

167

db.persistence.setAutocompactionInterval(30000);

168

169

// Stop automatic compaction

170

db.persistence.stopAutocompaction();

171

172

// Listen for compaction events

173

db.on('compaction.done', () => {

174

console.log('Database compaction completed');

175

});

176

```

177

178

### Event Handling

179

180

Database events for monitoring compaction and other operations.

181

182

```javascript { .api }

183

/**

184

* Database events (extends EventEmitter)

185

*/

186

interface DatastoreEvents {

187

'compaction.done': () => void; // Fired when compaction operation completes

188

}

189

```

190

191

**Usage Examples:**

192

193

```javascript

194

const db = new Datastore({ filename: './data.db', autoload: true });

195

196

// Listen for compaction completion

197

db.on('compaction.done', () => {

198

console.log('Database has been compacted');

199

console.log('File size optimized');

200

});

201

202

// Set up automatic compaction with event monitoring

203

db.persistence.setAutocompactionInterval(60000); // Every minute

204

205

db.on('compaction.done', () => {

206

const stats = require('fs').statSync(db.filename);

207

console.log('Current database size:', stats.size, 'bytes');

208

});

209

```