更新流星上的MongoDB收藏

update mongodb collection on meteor

本文关键字:MongoDB 收藏 流星 更新      更新时间:2023-09-26

我有一个Meteor应用程序来列出名称和号码,我可以插入和删除名称和数字,现在我正在尝试添加一个按钮来更改名称或数字字段如何在流星中做到这一点

这是我的代码

。.html

 <head>
    <title>Meteor_CRUD</title>
</head>
<body>
    {{> index}}
</body>
<template name="index">
    <h1>List</h1>
    <table> 
        <thead>
            <td>Name</td>
            <td>Number</td>
        </thead>
        <tbody>
            <tr>
                <td><input class="name" type="text"/></td>
                <td><input class="number" type="text"/></td>
                <td><button class="add">add</button></td>
        </tr>
        {{#each list}}
            <tr>
                <td>{{name}}</td>
                <td>{{number}}</td>
                <td><button class="del">del</button></td>
                <td><button class="change">change</button></td>
            </tr>
        {{/each}}
    </tbody>
</table>

。.js

List = new Meteor.Collection("list");
if (Meteor.isClient) {
Template.index.helpers({
    list : function () {
        return List.find();  
    }
});
Template.index.events({
    'click .del' : function (evt, tmpl) {
        List.remove(this._id);
    },
    'click .add' : function (evt, tmpl) {
        var name = tmpl.find(".name").value;
        var number = tmpl.find(".number").value;
        List.insert({name: name, number: number});
        tmpl.find(".name").value = '';
        tmpl.find(".number").value = '';
    },
    'click .change' : function (evt, tmpl) {
        //List.update(this._id);
    }
});
}
if (Meteor.isServer) {
   Meteor.startup(function () {
      // code to run on server at startup
   });
}

有人可以帮助我吗?

谢谢

如果要

更新字段,首先,使用某个字段(此处为_id)查找文档,然后将更改推送到文档中,如下所示

'click .change' : function (evt, tmpl) {
        //List.update(this._id);
         var name=this.name;
         var number=this.number;
         List.update({_id:this._id},{$push:{name:name,number:number}});
    }

通过在服务器端插入以下代码,确保您有权更新集合

List.allow({
            update:function(userId, doc, fields, modifier)
              {
            //anyone can update the collection
            //you can write some filters to restrict the updating to only owner of the document
               return true;
              }
        });