使用 Sails.js 将 JSON 保存到 MongoDb
Save JSON in MongoDb with Sails.js
我想做的是从外部创建我的数据库 API,首先我在我的 DBController 中创建一个函数 loadData(req, res){}
,这个函数以 JSON 格式加载数据来自 API。
我现在想做的是把这个返回的JSON保存在我的mongoDB里面,不知道怎么办。请问我该怎么做?
如果 JSON 表示与数据库结构匹配的记录数组,那么您需要做的就是加载文件并保存内容
var data = require('./datafile.json')
MODEL.create(data).exec(function(err,result){/*...*/})
- 确保在模块中添加了 sails-mongo 适配器,否则使用,
npm install sails-mongo --save
在 config/connections.js 中定义一个连接。如果你不使用其他数据库,你可以在 config/models.js 下将其设置为默认连接。
然后,您必须创建一个模型,其定义类似于外部 API 返回的 JSON 的内容。
例如。如果外部 API 正在返回。
[{
attribute1: '<value>',
attribute2: '<value>',
attribute3: '<value>'
}]
您需要在 /api/models 下创建一个名为 Model.js 的模型,如下所示,
module.exports = {
attributes: {
attribute1: {type: 'integer'},
attribute2: {type: 'string'},
attribute3: {type: 'datetime'}
}
};
请参阅 this 以了解有关创建模型的更多信息。
然后在你的控制器中就可以了,
var externalJSON = <API result JSON>;
Model.create(externalJSON)
.exec(function(err, user){
//Processing
});
我想做的是从外部创建我的数据库 API,首先我在我的 DBController 中创建一个函数 loadData(req, res){}
,这个函数以 JSON 格式加载数据来自 API。
我现在想做的是把这个返回的JSON保存在我的mongoDB里面,不知道怎么办。请问我该怎么做?
如果 JSON 表示与数据库结构匹配的记录数组,那么您需要做的就是加载文件并保存内容
var data = require('./datafile.json')
MODEL.create(data).exec(function(err,result){/*...*/})
- 确保在模块中添加了 sails-mongo 适配器,否则使用,
npm install sails-mongo --save
在 config/connections.js 中定义一个连接。如果你不使用其他数据库,你可以在 config/models.js 下将其设置为默认连接。
然后,您必须创建一个模型,其定义类似于外部 API 返回的 JSON 的内容。
例如。如果外部 API 正在返回。
[{
attribute1: '<value>',
attribute2: '<value>',
attribute3: '<value>'
}]
您需要在 /api/models 下创建一个名为 Model.js 的模型,如下所示,
module.exports = {
attributes: {
attribute1: {type: 'integer'},
attribute2: {type: 'string'},
attribute3: {type: 'datetime'}
}
};
请参阅 this 以了解有关创建模型的更多信息。
然后在你的控制器中就可以了,
var externalJSON = <API result JSON>; Model.create(externalJSON) .exec(function(err, user){ //Processing });