【发布时间】:2020-06-28 18:44:01
【问题描述】:
我正在创建我的收藏字段如下:
comments: {
type: [String, String],
label: 'CommentsLabel',
optional: true,
},
我希望 cmets 有键值对,其中用户 id 作为键,他的评论作为值,
当我尝试将值输入到集合中时,如下所示:
Drawings.update({_id: id}, {$set: {comments: [Meteor.userId(), document.getElementById('commentTextArea').value]}})
值已成功存储在集合中:
问题是上面的代码覆盖了值,我希望用户使用新的键、值对将新注释作为新注释推送到数组中,我已经尝试了$push 和$addToSet,如下所示:
Drawings.update({_id: id}, {$push: {comments:[Meteor.userId(), document.getElementById('commentTextArea').value]}});
Drawings.update({_id: id}, {$addToSet: {comments:[Meteor.userId(), document.getElementById('commentTextArea').value]}});
$push 和 $addToSet 在控制台中返回以下错误:
update failed: Error: CommentsLabel must be a string (comments.0) in drawings update
at getErrorObject (http://localhost:3000/packages/aldeed_collection2.js?hash=a69577047db366439087c686b90f269a3cd3a56a:579:17)
at doValidate (http://localhost:3000/packages/aldeed_collection2.js?hash=a69577047db366439087c686b90f269a3cd3a56a:548:13)
at Collection.Mongo.Collection.<computed> [as update] (http://localhost:3000/packages/aldeed_collection2.js?hash=a69577047db366439087c686b90f269a3cd3a56a:297:14)
at Object.click #addComment (http://localhost:3000/app/app.js?hash=e62868eba963926f7b9df35445920518c27ffe15:2303:18)
at http://localhost:3000/packages/blaze.js?hash=a20deb597f76789e171a9ee2b2e37d73fbb7ecda:3630:20
at Function.Template._withTemplateInstanceFunc (http://localhost:3000/packages/blaze.js?hash=a20deb597f76789e171a9ee2b2e37d73fbb7ecda:3575:14)
at Blaze.View.<anonymous> (http://localhost:3000/packages/blaze.js?hash=a20deb597f76789e171a9ee2b2e37d73fbb7ecda:3629:25)
at http://localhost:3000/packages/blaze.js?hash=a20deb597f76789e171a9ee2b2e37d73fbb7ecda:2426:28
at Object.Blaze._withCurrentView (http://localhost:3000/packages/blaze.js?hash=a20deb597f76789e171a9ee2b2e37d73fbb7ecda:2109:12)
at Blaze._DOMRange.<anonymous> (http://localhost:3000/packages/blaze.js?hash=a20deb597f76789e171a9ee2b2e37d73fbb7ecda:2425:24)
我尝试了以下方法:
var commentsLength = Drawings.findOne({_id: id}).comments.length;
Drawings.update({_id: id}, {$set: {'comments.commentsLength':[Meteor.userId(), document.getElementById('commentTextArea').value]}});
但即使我使用$set operator :slight_smile:
update failed: Access denied. In a restricted collection you can only update documents, not replace them. Use a Mongo update operator, such as '$set'.
并不是说即使我使用$push 运算符,我也会遇到同样的限制错误
以下是我对集合的允许和拒绝规则:
Drawings.allow({
insert: function(userId, doc){
return !!userId;
},
update: function(userId, doc){
return true;
},
remove: function(userId, doc){
return doc.authorId === userId;
}
});
如何正确地将新的键值对添加到 cmets 数组中?
【问题讨论】: