Обновление массива элементов внутри mongodb через EJS + Node [duplicate]

Вы можете сделать это с событиями перехода, так что вы так и есть, вы создаете 2 класса css для перехода, один из которых содержит анимацию другой, удерживая дисплей в состоянии none. и вы переключаете их после окончания анимации? В моем случае я могу отображать div снова, если я нажимаю btn и удаляю оба класса.

Попробуйте отрезать ниже ...

$(document).ready(function() {
  //assign transition event
  $("table").on("animationend webkitAnimationEnd", ".visibility_switch_off", function(event) {
    //we check if this is the same animation we want  
    if (event.originalEvent.animationName == "col_hide_anim") {
      //after the animation we assign this new class that basically hides the elements.    
      $(this).addClass("animation-helper-display-none");
    }

  });

  $("button").click(function(event) {

    $("table tr .hide-col").toggleClass(function() {
      //we switch the animation class in a toggle fashion...
      //and we know in that after the animation end, there is will the animation-helper-display-none extra class, that we nee to remove, when we want to show the elements again, depending on the toggle state, so we create a relation between them.
      if ($(this).is(".animation-helper-display-none")) {
        //im toggleing and there is already the above classe, then what we want it to show the elements , so we remove both classes...        
        return "visibility_switch_off animation-helper-display-none";
      } else {
        //here we just want to hide the elements, so we just add the animation class, the other will be added later be the animationend event...        
        return "visibility_switch_off";
      }

    });

  });

});
table th {
  background-color: grey;
}

table td {
  background-color: white;
  padding:5px;
}

.animation-helper-display-none {
  display: none;
}

table tr .visibility_switch_off {
  animation-fill-mode: forwards;
  animation-name: col_hide_anim;
  animation-duration: 1s;
}

@-webkit-keyframes col_hide_anim {
  0% {opacity: 1;}
  100% {opacity: 0;}
}

@-moz-keyframes col_hide_anim {
  0% {opacity: 1;}
  100% {opacity: 0;}
}

@-o-keyframes col_hide_anim {
  0% {opacity: 1;}
  100% {opacity: 0;}
}

@keyframes col_hide_anim {
  0%   {opacity: 1;}
  100% {opacity: 0;}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <theader>
    <tr>
      <th>Name</th>
      <th class='hide-col'>Age</th>
      <th>Country</th>
    </tr>
  </theader>
  <tbody>
    <tr>
      <td>Name</td>
      <td class='hide-col'>Age</td>
      <td>Country</td>
    </tr>
  </tbody>
</table>

<button>Switch - Hide Age column with fadeout animation and display none after</button>

52
задан Neurax 10 October 2015 в 06:41
поделиться

3 ответа

Предполагая, var friend = { firstName: 'Harry', lastName: 'Potter' };

Есть два варианта:

Обновление модели в памяти и сохранение (простой javascript array.push):

person.friends.push(friend);
person.save(done);

или

PersonModel.update(
    { _id: person._id }, 
    { $push: { friends: friend } },
    done
);

Я всегда стараюсь и выбираю первый вариант, когда это возможно, потому что он будет уважать больше преимуществ, которые дает вам мангуст (крючки, проверка и т. д.), ,

Однако, если вы делаете много одновременных записей, вы столкнетесь с условиями гонки, в результате чего вы столкнетесь с неприятными ошибками версий, чтобы остановить вас от замены всей модели каждый раз и потерять предыдущего добавленного вами друга , Так что только переходите к последнему, когда это абсолютно необходимо.

96
ответ дан reddisht 26 August 2018 в 06:38
поделиться

Оператор $ push добавляет указанное значение в массив.

{ $push: { <field1>: <value1>, ... } }

$ push добавляет поле массива со значением как своим элементом.

Выше ответ отвечает всем требованиям, но я получил его, выполнив следующие

var objFriends = { fname:"fname",lname:"lname",surname:"surname" };
Friend.findOneAndUpdate(
   { _id: req.body.id }, 
   { $push: { friends: objFriends  } },
  function (error, success) {
        if (error) {
            console.log(error);
        } else {
            console.log(success);
        }
    });
)
4
ответ дан Parth Raval 26 August 2018 в 06:38
поделиться

Я столкнулся с этим вопросом. Мое исправление заключалось в создании дочерней схемы. См. Ниже пример для ваших моделей.

---- Персональная модель

const mongoose = require('mongoose');
const SingleFriend = require('./SingleFriend');
const Schema   = mongoose.Schema;

const productSchema = new Schema({
  friends    : [SingleFriend.schema]
});

module.exports = mongoose.model('Person', personSchema);

*** Важно: SingleFriend.schema -> обязательно используйте строчные буквы для схемы

--- Схема ребенка

const mongoose = require('mongoose');
const Schema   = mongoose.Schema;

const SingleFriendSchema = new Schema({
  Name: String
});

module.exports = mongoose.model('SingleFriend', SingleFriendSchema);
-1
ответ дан theRealSheng 26 August 2018 в 06:38
поделиться
Другие вопросы по тегам:

Похожие вопросы: