所以,我从客户端接收一些 JSON 数据到我的 Node.JS 服务器。我想使用 Mongoose 将该 json 插入到我的 MongoDB 实例中。
我可以按原样插入 JSON,效果很好,因为它只是文本。但是,我想在插入之前对其进行解析,这样当我稍后提取它时,它就会非常整洁。
所以,这是可行的:
wordStream.words.push(wordData);
这不是:
wordStream.words.push(JSON.parse(wordData));
那么,我是否应该在插入之前解析 JSON?
如果我应该解析 JSON,我该怎么做才能不抛出错误?我需要将所有内容放在双引号“”中,我相信,在它解析之前,但出于某种原因,每当我用双引号创建一个字符串并解析它时,它都会把一切都弄错。
这是 JSON:
{ word: 'bundle',
definitions:
[ { definition: 'A group of objects held together by wrapping or tying.',
partOfSpeech: 'noun' } ],
urlSource: 'testurl',
otherSource: '' }
还有我尝试解析时的错误
/Users/spence450/Documents/development/wordly-dev/wordly-server/node_modules/mongoose/lib/utils.js:409
throw err;
^
SyntaxError: Unexpected token o
想法?
最佳答案
So, should I even want to parse the JSON before insertion?
当您需要在 MongoDB 数据库中进行查询时,将字符串转换为 JSON 对象会对您有所帮助。
And if I should parse the JSON, how do I do it without throwing an error? I need to put everything in double quotes "", I believe, before it will parse, but for some reason whenever I make a string with double quotes and parse it, it turns everything all wrong.
您没有收到 JSON 文档。 JSON 文档必须包含引用的键。
您可以:
关于node.js - 我应该在插入到 MongoDB 之前解析 JSON 数据吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16494629/