【问题标题】:Checking if field inside collection exists检查集合内的字段是否存在
【发布时间】:2019-06-16 21:40:13
【问题描述】:

我想检查集合字段中的值是否不存在。

我尝试了两种方法。据我所知,一旦检查它是否存在,结果就很好:

if (Characters.findOne({name:name})) {
      {throw new Meteor.Error('name exists');} };

当你输入一个已经存在的名字时,它会抛出错误。

现在我尝试了相反的方法

   if (  Characters.find( { name: { $not: { $eq: name } } } ) ) {
    {throw new Meteor.Error('name doesn't exist');}
 };

我预计只有在给出不存在的名称时才会引发错误。我当然注释了第一个代码。但是当传入一个确实存在的名称时,它也会抛出错误。

我尝试了很多不同的运算符,但结果总是一样。

编辑

我尝试了建议的方法,效果很好!

案例:名称确实存在:

Meteor.methods({
  'characters.start'(name) {
   check(name, String);

if (Characters.findOne({name})) {
    throw new Meteor.Error('name exists');
} else {
 return Characters.insert({
      name,
      owner: Meteor.user().username,
      ownerId: Meteor.userId(),

    });
  }
},

案例:名称不存在:

Meteor.methods({
  'characters.start'(name) {
   check(name, String);

if (Characters.findOne({name})) {
 return Characters.insert({
      name,
      owner: Meteor.user().username,
      ownerId: Meteor.userId(),
      });
} else {
  throw new Meteor.Error('name exists');
  }
},

感谢您的帮助!

【问题讨论】:

    标签: mongodb meteor


    【解决方案1】:

    您的查询不会像您希望的那样工作。将始终返回不匹配的名称。

    检查不存在只是它存在的逆:

    if (Characters.findOne({name})) {
        throw new Meteor.Error('name exists');
    } else {
        // It wasn't found, therefore it doesn't exist
        // - so you can create it now
    }
    

    我希望这是有道理的:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多