我的集合中有数组对象。当我尝试将数据更新到数组对象时,我得到额外的方括号。 这是代码。
var comments = [{
'COMMENTED_BY' : employee.SYSTEM_USER_ID,
'COMMENT' : employee.FIRST_NAME+" "+employee.LAST_NAME+" Started working on this comlaint"
}];
if(req.body.complaint.comment){
comments.push({'COMMENTED_BY' : employee.SYSTEM_USER_ID,'COMMENT': req.body.complaint.comment});
}
Complaint.findByIdAndUpdate(
req.body.complaint.complaintId,
{$set: {'STATUS': 1}, $push: {"COMMENTS": comments}},
{safe: true, upsert: true},
function(err, model) {
我的收藏如下所示
{
"COMMENT" : "media delete confirmation UI issue",
"COMMENTED_BY" : ObjectId("575cc0b39dd420a41d202dad"),
"_id" : ObjectId("575fe9e1a5ee92201b58011e"),
"CREATED_AT" : ISODate("2016-06-14T11:26:25.003Z")
},
{
"COMMENT" : "Could someone explain to me how Luke Ronchi gets in when Tom Latham is a very capable keeper as well as batsman? Why not another specialist batsman/bowler?",
"COMMENTED_BY" : ObjectId("575cc0b39dd420a41d202dad"),
"_id" : ObjectId("575fea19a5ee92201b58011f"),
"CREATED_AT" : ISODate("2016-06-14T11:27:21.136Z")
},
[
{
"COMMENT" : "media delete confirmation UI issue",
"COMMENTED_BY" : ObjectId("575cc0b39dd420a41d202dad"),
"_id" : ObjectId("575fe9e1a5ee92201b58011e"),
"CREATED_AT" : ISODate("2016-06-14T11:26:25.003Z")
},
{
"COMMENT" : "Could someone explain to me how Luke Ronchi gets in when Tom Latham is a very capable keeper as well as batsman? Why not another specialist batsman/bowler?",
"COMMENTED_BY" : ObjectId("575cc0b39dd420a41d202dad"),
"_id" : ObjectId("575fea19a5ee92201b58011f"),
"CREATED_AT" : ISODate("2016-06-14T11:27:21.136Z")
}
]
我想删除额外的[]括号
答案 0 :(得分:0)
这种情况正在发生,因为您只是在更新时将对象数组comment
推送到COMMENTS
数组字段中。在推送对象数组时使用$each
代替。
有关详细信息,请参阅doc-$each。
尝试以下查询。 : -
Complaint.findByIdAndUpdate(
req.body.complaint.complaintId,
{$set: {'STATUS': 1}, $push: {"COMMENTS":{$each : comments}},
{safe: true, upsert: true})
希望这能解决您的问题。