MongoDB
 sql >> Database >  >> NoSQL >> MongoDB

Estrarre una voce da un array tramite Meteor

Per un'applicazione meteor di base, chiamo "bunk" su questo. Se crei un nuovo progetto e definisci semplicemente la collezione, allora il $pull l'operatore funziona come previsto:

Console:

meteor create tickets
cd tickets
meteor run

Quindi apri una shell e inserisci i tuoi dati:

meteor mongo

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

Quindi basta produrre un codice e un modello di base:

ticker.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
  });
}

ticker.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>

L'applicazione dovrebbe funzionare correttamente, quindi nella console del browser esegui .update() (rientrato per la lettura):

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

E l'elemento viene rimosso dalle voci e la pagina viene aggiornata senza l'elemento. Quindi tutto finito, proprio come previsto.

Anche l'aggiunta dei pacchetti SimpleSchema e Collection2 non fa differenza qui:

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

ticker.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
  });
}

Reinizializza i dati ed esegui lo stesso comando nella console del browser e tutto rimane lo stesso.

Controlla questo o qualsiasi errore di battitura nelle tue operazioni o altre differenze per avere un'idea del motivo per cui questo non funziona per te.

Lo suggerirei vivamente, poiché "ricominciare da capo" in questo modo mostra il comportamento previsto e, se vedi un comportamento diverso, è probabile che si tratti di un problema con un altro plug-in che hai installato.

Ma in genere funziona.