[英]How to insert only if it doesnt exist in Meteor
我正在尝试使用html中的表单更新主题集合。 当我使用topic.insert()时,我可以将每个文档添加到集合中,但是如果使用update则不起作用。 我只想将文档添加到集合中(如果尚不存在)。
Topics = new Mongo.Collection("Topics");
if(Meteor.isClient){
Template.body.helpers({
topic: function(){
return Topics.find({});
}
});
Template.body.events({
"submit .new-topic": function(event){
//prevent reload on submit
event.preventDefault();
//get content from form
var title = event.target.title.value;
var subtopic = event.target.subtopic.value;
var content = event.target.content.value;
var video = event.target.video.value;
Topics.update({
title: title},{
title: title,
subtopic: subtopic,
content: content,
video: video
},
{upsert: true}
);
//clear forms
event.target.title.value = "";
event.target.subtopic.value = "";
event.target.content.value="";
event.target.video.value="";
}
});
}
您应该使用upsert
。
更新+插入的混合
Topics.upsert({
// Selector
title:title
}, {
// Modifier
$set: {
...
}
});
我将为您提供广泛的概述类型的答案。
第一步是您需要检查您的条目是否存在。
var collectionEntry = Topics.find({title:title});
如果找到一个,则可以对其进行更新。
Topics.update({title:title},$set{ ... })
如果找不到,则将其插入。
Topics.insert({ ... })
使用此处的文档了解如何更新mongo集合。 http://docs.mongodb.org/manual/reference/operator/update/set/
另外,您实际上应该通过文档ID进行更新,并且应该将其作为“流星方法”进行更新,而不是从客户端进行更新。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.