我正在尝试使用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: {
        ...
    }
});


See Meteor Docs (collection.upsert).

关于javascript - 仅当 meteor 中不存在时如何插入,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33110064/

10-12 00:14
查看更多