我在mongoose中有这个“架构”,在我的字典中有一个数组并有其他嵌入式数组,
如果没有嵌入对象,我可以保存,如何保存嵌入对象?
var ReportSchema = new Schema({
appVersion: { type: String, required: true},
osVersion: { type: String, required: true},
deviceType: { type: String, required: true},
userID: { type: String, required: true},
sessionIDtimestamp: { type: String, required: true},
eventItem : [new Schema ({
eventType:{type :String},
startTime:{type :String},
endTime:{type :String},
params:[new Schema ({
val:{type :String}
})]
})]
});
在我的路由器上:
apiRouter.route('/report')
.post(function(req, res) {
var report = new Report();
report.appVersion = req.body.appVersion;
report.osVersion = req.body.osVersion;
report.deviceType = req.body.deviceType;
report.userID = req.body.userID;
report.sessionIDtimestamp = req.body.sessionIDtimestamp;
for (var i = req.body.events.length - 1; i >= 0; i--) {
var requestStringa = util.inspect(req.body.events, {showHidden: false, depth: null});
console.log("entro :"+requestStringa);
};
report.save(function(err) {
if (err) {
return res.send(err);
}
res.json({ message: 'report created!' });
});
})
我也不认为枚举数组的方式很好吗?
编辑 事件日志
entro :[ { eventType: 'Account_Rated_Pressed',
startTime: '1435819399',
endTime: '1435819399',
params: [ { paramKey: 'rating', paramValue: '5' } ] },
{ eventType: 'RateableDetail',
startTime: '1435819399',
endTime: '1435819399',
params: [ { paramKey: 'rating', paramValue: '5' } ] } ]
如何保存我的嵌入对象欢呼声
答案 0 :(得分:1)
要保存嵌入文档,只需为数组字段eventItem
分配请求对象值,如下所示:
apiRouter.route('/report')
.post(function(req, res) {
var report = new Report();
report.appVersion = req.body.appVersion;
report.osVersion = req.body.osVersion;
report.deviceType = req.body.deviceType;
report.userID = req.body.userID;
report.sessionIDtimestamp = req.body.sessionIDtimestamp;
report.eventItem = req.body.events;
report.save(function(err) {
if (err) {
return res.send(err);
}
res.json({ message: 'report created!' });
});
})
在req.body.event
是对象而不是数组的情况下,您需要使用JavaScript push()
方法将对象推送到数组。比如说,如果req.body.event
具有结构
{
eventType: 'Account_Rated_Pressed',
startTime: '1435819399',
endTime: '1435819399',
params: [ { paramKey: 'rating', paramValue: '5' } ]
}
然后你可以做
apiRouter.route('/report')
.post(function(req, res) {
var report = new Report();
report.appVersion = req.body.appVersion;
report.osVersion = req.body.osVersion;
report.deviceType = req.body.deviceType;
report.userID = req.body.userID;
report.sessionIDtimestamp = req.body.sessionIDtimestamp;
report.eventItem.push(req.body.event);
report.save(function(err) {
if (err) {
return res.send(err);
}
res.json({ message: 'report created!' });
});
})