我已经学习Meteor大约3个星期了,我仍然试图围绕更新/查询集合。我正在尝试构建一个Slack克隆,并使用一组fixture文档创建了以下集合:
Conversations.insert({
channel: "#defaultChannel",
createdBy: "coffeemeup",
timestamp: new Date(),
followers: ["username1", "username2"],
entries: [
{
message: "this is a message #1",
postedTime: new Date(),
author: "coffeemeup"
}]
});
我尝试使用下面的代码将另一个文档插入条目数组。但这不仅不起作用,它会引发一个对象的[[原型]]变异会导致你的代码运行得很慢...... "错误。我真的很感激一些帮助!
Conversations.update({
channel: "#defaultChannel"
}, {
$push: {
entries: {
message: newMessage,
postedTime: new Date(),
author: "coffeemeup"
}
}
});
另外,我很想听听有关如何更好地构建/设计此数据库以构建Slack克隆的建议。
答案 0 :(得分:1)
如果要在客户端上运行更新操作,则需要使用_id
字段。否则你会收到这个错误:
错误:不允许。不受信任的代码只能按ID更新文档。 [403]
因此,首先获取文档,然后使用文档_id
运行更新查询。
例如:
var conversation = Conversations.findOne({
"channel": "#defaultChannel"
});
Conversations.update({
_id: conversation._id
}, {
$push: {
entries: {
message: "newMessage",
postedTime: new Date(),
author: "coffeemeup"
}
}
});
以下是更新后的对话文档:
{
"_id": "wGixGJgoM6fk57mtN",
"channel": "#defaultChannel",
"createdBy": "coffeemeup",
"timestamp": "2015-07-27T19:25:52.842Z",
"followers": [
"username1",
"username2"
],
"entries": [
{
"message": "this is a message #1",
"postedTime": "2015-07-27T19:25:52.842Z",
"author": "coffeemeup"
},
{
"message": "newMessage",
"postedTime": "2015-07-27T19:27:54.930Z",
"author": "coffeemeup"
}
]
}