我在我的Meteor 1.1.0.2应用程序中有以下(简化的)SimpleSchema模式:
Tickers.attachSchema(
new SimpleSchema({
entries: {
type: [TickerEntries],
defaultValue: [],
optional: true
}
})
);
TickerEntries = new SimpleSchema({
id: {
type: String,
autoform: {
type: "hidden",
label: false,
readonly: true
},
optional: true,
autoValue: function () {
if (!this.isSet) {
return new Mongo.Collection.ObjectID()._str;
}
}
},
text: {
type: String,
label: 'Text'
}
};
我在数据库中有以下条目:
{
"_id" : "ZcEvq9viGQ3uQ3QnT",
"entries" : [
{
"text" : "a",
"id" : "fc29774dadd7b37ee0dc5e3e"
},
{
"text" : "b",
"id" : "8171c4dbcc71052a8c6a38fb"
}
]
}
我希望删除指定ID的entries数组中的一个条目。
如果我在meteor-mongodb-shell中执行以下命令,它将可以顺利工作:
db.Tickers.update({_id:"3TKgHKkGnzgfwqYHY"}, {"$pull":{"entries": {"id":"8171c4dbcc71052a8c6a38fb"}}})
但问题是,如果我在Meteor内部执行同样的操作,它就不起作用。这是我的代码:
Tickers.update({id: '3TKgHKkGnzgfwqYHY'}, {$pull: {'entries': {'id': '8171c4dbcc71052a8c6a38fb'}}});
我还尝试了以下方法:
Tickers.update('3TKgHKkGnzgfwqYHY', {$pull: {'entries': {'id': '8171c4dbcc71052a8c6a38fb'}}});
这些命令都没有报错,但它们并没有从我的文档中删除任何内容。
可能是$pull
命令没有得到正确支持,或者我犯了错误?
谢谢提前!
编辑:
我找到了问题,但在我的描述中看不到它,因为我简化了架构。在我的应用程序中,TickerEntries
有一个额外的属性timestamp
:
TickerEntries = new SimpleSchema({
id: {
type: String,
optional: true,
autoValue: function () {
if (!this.isSet) {
return new Mongo.Collection.ObjectID()._str;
}
}
},
timestamp: {
type: Date,
label: 'Minute',
optional: true,
autoValue: function () {
if (!this.isSet) { // this check here is necessary!
return new Date();
}
}
},
text: {
type: String,
label: 'Text'
}
});
感谢Kyll的提示,我创建了一个Meteorpad,并发现autovalue
函数是导致问题的原因。
我现在已经将该函数更改为以下代码:
autoValue: function () {
if (!this.isSet && this.operator !== "$pull") { // this check here is necessary!
return new Date();
}
}
现在已经可以工作了。似乎在拉取项目/对象时返回自动值时,它会取消拉取操作,因为该值未设置为返回的值(因此时间戳属性保留旧值但未被拉取)。
这是相应的Meteorpad测试(只需注释掉autovalue函数中的运算符检查即可):http://meteorpad.com/pad/LLC3qeph66pAEFsrB/Leaderboard 感谢您所有人的帮助,您所有的帖子对我非常有帮助!
$pull
的预期行为,它应该有助于缩小您可能遇到的任何问题。 - Blakes Seven