通过 Meteor 从数组中提取条目 [英] Pull an entry from an array via Meteor

查看:15
本文介绍了通过 Meteor 从数组中提取条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 Meteor 1.1.0.2 应用程序中有以下(简化的)SimpleSchema 架构:

I've the following (simplified) SimpleSchema schema in my Meteor 1.1.0.2 app:

Tickers.attachSchema(
    new SimpleSchema({
        entries: {
            type: [TickerEntries],
            defaultValue: [],
            optional: true
        }
    })
);

TickerEntries = new SimpleSchema({
    id: {
        type: String,
        autoform: {
            type: "hidden",
            label: false,
            readonly: true
        },
        optional: true,
        autoValue: function () {
            if (!this.isSet) {
                return new Mongo.Collection.ObjectID()._str;
            }
        }
    },
    text: {
        type: String,
        label: 'Text'
    }
};

在数据库中,我确实有以下条目:

In the database I do have the following entries:

{
    "_id" : "ZcEvq9viGQ3uQ3QnT",
    "entries" : [
        {
            "text" : "a",
            "id" : "fc29774dadd7b37ee0dc5e3e"
        },
        {
            "text" : "b",
            "id" : "8171c4dbcc71052a8c6a38fb"
        }
    ]
}

我想删除由 ID 指定的条目数组中的一个条目.

I'd like to remove one entry in the entries array specified by an ID.

如果我在meteor-mongodb-shell中执行以下命令,它就可以正常工作:

If I execute the following command in the meteor-mongodb-shell it works without problems:

db.Tickers.update({_id:"3TKgHKkGnzgfwqYHY"}, {"$pull":{"entries": {"id":"8171c4dbcc71052a8c6a38fb"}}})

但问题是,如果我要在 Meteor 中做同样的事情,那是行不通的.这是我的代码:

But the problem is, that if I'm going to do the same from within Meteor, it doesn't work. Here's my code:

Tickers.update({id: '3TKgHKkGnzgfwqYHY'}, {$pull: {'entries': {'id': '8171c4dbcc71052a8c6a38fb'}}});

我还尝试了以下方法:

Tickers.update('3TKgHKkGnzgfwqYHY', {$pull: {'entries': {'id': '8171c4dbcc71052a8c6a38fb'}}});

这些命令都没有给我一个错误,但它们不会从我的文档中删除任何内容.

None of these commands give me an error, but they don't remove anything from my document.

可能是 $pull 命令没有得到正确支持还是我在某处犯了错误?

Could it be possible, that the $pull command isn't supported properly or do I have made a mistake somewhere?

提前致谢!

我发现了在我的描述中看不到的问题,因为我已经简化了我的架构.在我的应用程序中,TickerEntries 中有一个附加属性 timestamp:

I've found the problem, which couldn't be seen in my description, because I've simplified my schema. In my app there's an additional attribute timestamp in TickerEntries:

TickerEntries = new SimpleSchema({
    id: {
        type: String,
        optional: true,
        autoValue: function () {
            if (!this.isSet) {
                return new Mongo.Collection.ObjectID()._str;
            }
        }
    },
    timestamp: {
        type: Date,
        label: 'Minute',
        optional: true,
        autoValue: function () {
            if (!this.isSet) { // this check here is necessary!
                return new Date();
            }
        }
    },
    text: {
        type: String,
        label: 'Text'
    }
});

感谢 Kyll 的提示,我创建了一个 Meteorpad 并发现 autovalue 函数导致了问题.

Thanks to the hint from Kyll, I've created a Meteorpad and found out, that the autovalue function is causing the problems.

我现在已将函数更改为以下代码:

I've now changed the function to the following code:

autoValue: function () {
    if (!this.isSet && this.operator !== "$pull") { // this check here is necessary!
        return new Date();
    }
}

现在它正在工作.看来,在拉动项目/对象的情况下返回自动值值,它取消拉动操作,因为该值未设置为返回值(因此时间戳属性保留旧值但未拉动).

And now it is working. It seems, that returning a autovalue-value in the case of pulling an item/object, it cancels the pull operation, as the value isn't set to the returned value (so the timestamp attribute keeps the old value but isn't pulled).

这里是根据 Meteorpad 对其进行测试(只需注释掉 autovalue 函数中的运算符检查):http://meteorpad.com/pad/LLC3qeph66pAEFsrB/排行榜

Here's the according Meteorpad to test it (simply comment out the check for the operator in the autovalue function): http://meteorpad.com/pad/LLC3qeph66pAEFsrB/Leaderboard

谢谢大家的帮助,你们所有的帖子都对我很有帮助!

Thank you all for your help, all your posts were very helpful to me!

推荐答案

对于基本的流星应用程序,我称之为bunk".如果您创建一个全新的项目并简单地定义集合,则 $pull 运算符按预期工作:

For a basic meteor application, I call "bunk" on this. If you create a brand new project and simply define the collection, then the $pull operator works as expected:

控制台:

meteor create tickets
cd tickets
meteor run

然后打开一个 shell 并插入你的数据:

Then open up a shell and insert your data:

meteor mongo

> db.tickets.insert(data)   // exactly your data in the question

然后只生成一些基本的代码和模板:

Then just produce some basic code and template:

tickers.js

Tickers = new Meteor.Collection("tickers");

if (Meteor.isClient) {

  Template.body.helpers({
    "tickers": function() {
      return Tickers.find({});
    }
  });

}

if (Meteor.isServer) {
  Meteor.startup(function () {
    // code to run on server at startup
  });
}

tickers.html

<head>
  <title>tickers</title>
</head>

<body>
  <h1>Welcome to Meteor!</h1>

  <ul>
    {{#each tickers}}
      {{> ticker}}
    {{/each}}
  </ul>

</body>

<template name="ticker">
  <li>
    {{_id}}
    <ul>
      {{#each entries}}
        {{> entry }}
      {{/each}}
    </ul>
  </li>
</template>

<template name="entry">
  <li>{{ id }} - {{text}}</li>
</template>

应用程序应该运行良好,因此在您的浏览器控制台中执行 .update()(缩进以供阅读):

The application should be running fine, so in your browser console do the .update() (indented for reading):

Tickers.update(
    { "_id": "ZcEvq9viGQ3uQ3QnT" },
    { "$pull": { "entries": { "id": "fc29774dadd7b37ee0dc5e3e" } }}
)

并且该项目从条目中删除,并且页面在没有该项目的情况下刷新.一切都过去了,正如预期的那样.

And the item is removed from entries and the page is refreshed without the item. So all gone, just as expected.

甚至添加 SimpleSchemaCollection2 包,这里没有区别:

Even adding the SimpleSchema and Collection2 packages, makes no difference here:

 meteor add aldeed:simple-schema
 meteor add aldeed:collection2

tickers.js

Tickers = new Meteor.Collection("tickers");

TickerEntries = new SimpleSchema({
  "id": {
    type: String,
    optional: true,
    autoValue: function() {
      if (!this.isSet) {
        return new Mongo.Collection.ObjectID()._str
      }
    }
  },
  "text": {
    type: String
  }
});

Tickers.attachSchema(
  new SimpleSchema({
    entries: { type: [TickerEntries] }
  })
);


if (Meteor.isClient) {

  Template.body.helpers({
    "tickers": function() {
      return Tickers.find({});
    }
  });

}

if (Meteor.isServer) {
  Meteor.startup(function () {
    // code to run on server at startup
  });
}

重新初始化数据并在浏览器控制台中运行相同的命令,一切都保持不变.

Re-initialize the data and run the same command in the browser console and everything stays the same.

检查此或您自己操作中的任何打字错误或其他差异,以了解为什么这对您不起作用.

Check this or any typing mistakes in your own operations or other differences for a clue as to why this does not work for you.

我强烈建议这样做,因为像这样的重新开始"显示了预期的行为,如果您看到不同的行为,则可能是您安装的另一个插件有问题.

I would suggest this strongly, as "starting fresh" like this shows the expected behavior, and if you are seeing different behavior then it is likely an issue with another plugin you have installed.

但一般来说,这是有效的.

But generally, this works.

这篇关于通过 Meteor 从数组中提取条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆