我正在尝试在mongodb中保存文档。没有任何成功。
JSON:
{
"ticketType": "Enquiry",
"type": "AA",
"subType": "BB",
"subSubType": "CC",
"misidnProfile": {
"serviceTypes": [
"Postpaid", "Prepaid"
],
"circles": [
"AA", "BB"
]
}
}
猫鼬模型:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var misidnProfile = new Schema({
serviceTypes: [String],
circles: [String],
});
var taggingProfile = new Schema({
ticketType: {type:String, required: true},
type: {type:String, required: true},
subType: {type:String, required: true},
subSubType: {type:String, required: true},
misidnProfile: {misidnProfile},
});
module.exports = mongoose.model("TaggingProfile", taggingProfile);
保存数据的代码:
module.exports.createTaggingProfile = function(req, res){
var taggingProfile = new TaggingProfile(req.body);
taggingProfile.save(function (err, tg) {
if(err){
return res.status(500).json({
title: 'An error occurred',
error: err
});
}
res.status(200).json({
message: 'Saved TaggingProfile',
obj: tg
});
});
};
它是保存taggingProfile但不是子文档msisdnProfile。我无法理解问题出在哪里?
修改 现在它正在储蓄。谢谢@Neil 在更新文档时,我发送JSON为
{
"ticketType": "Enquiry",
"type": "AA",
"subType": "BB",
"subSubType": "CC",
"misidnProfile": {
"serviceTypes": [
"Postpaid", "Prepaid", "ABC","PQR"
],
"circles": [
"AA", "BB"
]
}
}
奇怪的是,当我试图通过id查找文档时,我得到了TaggingProfile对象,但它没有msisdnProfile值。 检查以下代码。
TaggingProfile.findById(req.params.id, function (err, tg) {
if (err) {
return res.status(500).json({
title: 'An error occurred',
error: err
});
}
if (!tg) {
return res.status(500).json({
title: 'No TaggingProfile Found!',
error: {message: 'Message not found'}
});
}
req.taggingProfile=tg;
if(tg.misidnProfile){
console.log("## tg.misidnProfile PRofile present");
} else {
console.log("## tg.misidnProfile Not present");
}
for(var p in req.body){
req.taggingProfile[p] = req.body[p];
}
req.taggingProfile.save(function (err, result) {
if (err) {
return res.status(500).json({
title: 'An error occurred',
error: err
});
}
res.status(200).json({
message: 'Updated message',
obj: result
});
});
});