var myobj = {
"date": "24062014",
"class" : "a",
"student details" : [
{
"student name" : "xyz"
"studentid" : "a1"
"student marks": {
"maths" : "50"
"science" : "60"
}
},
{
"student name" : "tyr"
"studentid" : "a2"
"student marks": {
"maths" : "40"
"science" : "50"
}
}
]
}
问题:
如何以
的形式显示 someid - student name {
"studentname" :"somename "
"marks" : "somemarks "
}
上述所有格式的学生都可以保存到mongodb吗?如果是,我们如何将每次迭代保存到db?
答案 0 :(得分:0)
你的问题不是很清楚,看起来像一个措辞不好的重写家庭作业问题,但看看这对你有什么帮助:
var _ = require('lodash')
var studentsByID = {};
_.each(myobj["student details"], function (student) {
studentsByID[student.studentid] = {
studentname: student["student name"],
marks: _.values(student["student marks"])
};
});
console.log(studentsByID);
关于将对象作为文档保存到数据库,是的,当然可以保存它们。
var MongoClient = require('mongodb').MongoClient,
async = require('async');
MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
if(err) throw err;
var collection = db.collection('students');
async.map(
studentsByID,
function (studentDetails, doneInserting) {
collection.insert(studentDetails, doneInserting);
},
function (err, results) {
console.log(err, results);
db.close();
}
);
});