我正在尝试使用 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
。
Blend of update + insert
Topics.upsert({
// Selector
title:title
}, {
// Modifier
$set: {
...
}
});
关于javascript - 如何仅在 Meteor 中不存在时插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33110064/