仅当流星中不存在时如何插入

azd*_*fg1 0 javascript 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="";
            }
            });
}   
Run Code Online (Sandbox Code Playgroud)

Nic*_*ier 5

您应该使用upsert

混合更新+?插入

Topics.upsert({
    // Selector
    title:title
}, {
    // Modifier
    $set: {
        ...
    }
});
Run Code Online (Sandbox Code Playgroud)

请参阅流星文档(collect.upsert)。