我有reportSchema.js
,这是定义我的架构的地方。我将从Microsoft Graph API
返回的JSON存储到名为result
的变量中。我想将result
数组中的每个值存储到mongodb
中。我可以像这样从数组访问单个项目
receivedDateTime: result.value[0].receivedDateTime,
sentDateTime: result.value[1].sentDateTime
但是我希望能够一次存储所有内容。我该怎么做呢?我将在下面发布代码。
reportSchema
var mongoose = require('mongoose')
var sera = mongoose.Schema({
isRead: Boolean,
subject: String,
from: String,
receivedDateTime: Date,
sentDateTime: Date
});
module.exports = mongoose.model("SERA", sera)
sample of result array
value: [{
'@odata.etag': 'W/"CQAAAA=="',
id: 'AAMkADg4MTBkNmRiLTAwNzQtNDE1Ny1hNjlkLWVjNzE5N2M1MGEwMgBGAAAAAAA9yT6uaq2hTrV0L6GqHQ_CBwALVVFnK27cQ4tC6FzqOc3cAAAAAAEMAAALVVFnK27cQ4tC6FzqOc3cAANuNGz-AAA=',
receivedDateTime: '2019-03-09T03:45:45Z',
sentDateTime: '2019-03-09T03:45:44Z',
subject: 'Re: hw3',
isRead: true,
from: {
emailAddress: {
name: 'Example',
address: 'example.yahoo.com'
}
}
}]
how I am saving the report
SERA.insertMany(result.value, function (error, success) {
if (error) {
console.log("There has been an error inserting")
} else {
console.log("The API data has been stored")
}
})
// save stores into database
SERA.save().then(result => {
console.log(result)
}).catch(function (error) {
console.log("The error is " + error)
});
res.status(201).json({
message: "Handling post request to /api/report",
createdReport: report
});
答案 0 :(得分:1)
您可以使用insertMany()接受要保存的值数组。
var mongoose = require('mongoose')
var sera = mongoose.Schema({
isRead: Boolean,
subject: String,
from: {
emailAddress: {
name: String,
address: String
}
},
receivedDateTime: Date,
sentDateTime: Date
});
const Sera = mongoose.model("SERA", sera)
const values = [{
id: 'AAMkADg4MTBkNmRiLTAwNzQtNDE1Ny1hNjlkLWVjNzE5N2M1MGEwMgBGAAAAAAA9yT6uaq2hTrV0L6GqHQ_CBwALVVFnK27cQ4tC6FzqOc3cAAAAAAEMAAALVVFnK27cQ4tC6FzqOc3cAANuNGz-AAA=',
receivedDateTime: '2019-03-09T03:45:45Z',
sentDateTime: '2019-03-09T03:45:44Z',
subject: 'Re: hw3',
isRead: true,
from: {
emailAddress: {
name: 'Example',
address: 'example.yahoo.com'
}
}
}]
Sera.insertMany(values, (error, docs) => {
if(error) {
console.log(error);
} else {
console.log(docs);
}
});
// alternative
// Sera.insertMany(values).then(docs => {
// console.log(docs)
// })
// .catch(error => {
// console.log(error)
// })