我无法获得正确运行的最简单的NeDB示例。我的代码仅在内存中工作,文件持久性保持失败而没有任何错误消息。
loaddatabase和insert事件的错误回调总是将空引用作为错误传递,因此没有信息。奇怪的是,似乎没有其他人有这个问题,所以我想我在这里遗漏了一些东西。非常感谢所有帮助。
以下是代码:
var Datastore = require('nedb'), db = new Datastore({ filename: 'test.db' });
db.loadDatabase(function (err) {
alert(err); // err is null, with the autoload flag no error is thrown either
});
var doc = { hello: 'world'};
db.insert(doc, function (err, newDoc) {
alert(err); // err is null here as well. Doc will be in the memory storage but no persisted to file
});

答案 0 :(得分:1)
虽然这个问题已经很久了,但我想与任何面临类似问题的人分享我的经验。
尝试
var Datastore = require('nedb'), db = new Datastore({ filename: 'test.db' });
db.loadDatabase(function (error) {
if (error) {
console.log('FATAL: local database could not be loaded. Caused by: ' + error);
throw error;
}
console.log('INFO: local database loaded successfully.');
});
// creating the object with new, just to make it clear.
// var doc = {hello: 'world'}; should work too.
function myDoc(greeting)
{
this.hello=greeting;
}
var doc = new myDoc('world');
db.insert(doc, function (error, newDoc) {
if (error) {
console.log('ERROR: saving document: ' + JSON.stringify(doc) + '. Caused by: ' + error);
throw error;
}
console.log('INFO: successfully saved document: ' + JSON.stringify(newDoc));
});
也许它有助于某人。 :)
答案 1 :(得分:0)
这个问题已经很老了,但是由于我遇到了非常类似的问题,我认为我将为遇到类似问题的任何人写出解决方案。
就我而言,我正在使用electron-webpack作为应用程序构建器来编写Electron应用程序。事实证明,Webpack加载的NeDB正在浏览器模式下运行,而无法访问文件系统。
要使其正常运行,我必须将导入语句从以下位置更改:
import DataStore from 'nedb';
对此:
const DataStore = require('nedb');
我还必须将NeDB作为外部模块(在package.json中)添加到Webpack配置中:
"electronWebpack": {
"externals": {
"nedb": "commonjs nedb"
}
}
我已经在NeDB github页面上找到了此解决方案:https://github.com/louischatriot/nedb/issues/329