Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/meteor/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Meteor 确保用户在更新时拥有文档的最有效方法?_Meteor - Fatal编程技术网

Meteor 确保用户在更新时拥有文档的最有效方法?

Meteor 确保用户在更新时拥有文档的最有效方法?,meteor,Meteor,我正在使用Meteor方法来更新文档,这样我可以更轻松地共享它们并拥有更多的控制权。但是,我在检查所有权时遇到了一个问题 我应该如何检查以确保调用update方法的用户是文档的所有者?目前,我先抓取文档,然后运行更新 有没有更好的模式来实现这一点 Meteor.methods({ 'Listing.update': function(docId, data) { var doc = db.listings.findOne({_id: docId}) || {}; if

我正在使用Meteor方法来更新文档,这样我可以更轻松地共享它们并拥有更多的控制权。但是,我在检查所有权时遇到了一个问题

我应该如何检查以确保调用update方法的用户是文档的所有者?目前,我先抓取文档,然后运行更新

有没有更好的模式来实现这一点

Meteor.methods({

  'Listing.update': function(docId, data) {

    var doc = db.listings.findOne({_id: docId}) || {};

    if (doc.userId !== this.userId) {
      throw new Meteor.Error(504, "You don't own post");
    }

    // ensure data is the type we expect
    check(data, {
      title: String,
      desc: String
    });

    return db.listings.update(docId, {$set: data});
  }

});

您不需要额外的db调用来获取原始文档,只需在
update
选择器中将
userId
作为额外的条件即可。如果不存在具有正确
\u id
用户id
的文档,则不会进行更新<代码>更新返回更新的文档数,因此成功时返回1,失败时返回0

像这样:

'Listing.update': function(docId, data) {

  var self = this;
  check(data, {
    title: String,
    desc: String
  });

  if ( ! self.userId ) 
    throw new Meteor.Error(500, 'Must be logged in to update listing');

  res = db.listings.update({_id: docId, userId: self.userId}, {$set: data});

  if ( res === 0 )
    throw new Meteor.Error( 504, "You do not own a post with that id" );

  return res;
}

此外,如果使用
findOne
检查文档是否存在,请使用fields选项限制从数据库返回的内容。通常只需
{fields:{u id:1}}

谢谢!!那将非常有效。我不需要确切地知道所有权本身失败,所以返回计数为0就可以了!