我有一个嵌入式文档如下:
var artist = new Schema({
name: {
type: String,
trim:true,
required:'Please fill artist name'
},
role : {
type: String,
trim: true,
default: ''
},
isPrimary : {
type: Boolean,
trim: false,
}
});
和其他文件如下:
var AlbumSchema = new Schema({
language: {
type: String,
default: '',
trim: true
},
artists: [artist],
title: {
type: String,
default: '',
required: 'Please fill Album title',
trim: true
});
当我发送请求和打印req.body值时,我得到如下所示:
{
title: 'Demo Add',
artists:
'[{"name":"Ilesh","role":"Performer","isPrimary":true,"$$hashKey":"ob
ject:227"}]',
language:'EN'
}
但是只要我将其转换为对象
var album = new Album(req.body);
并打印相册比我得到的结果如下:
{
title: 'Demo Add',
artists: [],
language: 'English'
}
我不知道为什么艺术家的价值在案件中变得无效。
编辑:
exports.SaveAlbum = function(req,res){
var album = new Album(req.body);
var data = _.pick(req.body, 'type')
, uploadPath = path.normalize('/album_uploads')
, file = req.files.file;
var user = req.user;
album.cover_art_path = file.path;
if (user) {
var upsertData = album.toObject();
delete upsertData._id;
Album.update({_id: album.id}, upsertData, {upsert: true},function(err)
{
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
}
else {
res.json(album);
}
});
} else {
res.status(400).send({
message: 'User is not signed in'
});
}
};
答案 0 :(得分:1)
&#39>''在数组中如下所述。当发送req.body时,这就是问题的起源。
你的要求是:
{
title: 'Demo Add',
artists: '[{"name":"Ilesh","role":"Performer","isPrimary":true,"$$hashKey":"ob
ject:227"}]',
language:'EN'
}
必须是:
{
title: 'Demo Add',
artists: [{"name":"Ilesh","role":"Performer","isPrimary":true,"$$hashKey":"ob
ject:227"}],
language:'EN'
}
此引号使艺术家成为字符串,而不是数组,然后在保存时失败。
然后,解决方案是:
var album = new Album(req.body);
album.artists = JSON.parse(req.body.artists);
希望能有所帮助。
谢谢