Jak usunąć dokumenty za pomocą węzła.js Mangusta?

FBFriendModel.find({
    id: 333
}, function (err, docs) {
    docs.remove(); //Remove all the documents that match!
});

Powyższe nie działa. Akta wciąż tam są.

Czy ktoś może to naprawić?
Author: KARTHIKEYAN.A, 2011-04-27

18 answers

Jeśli nie masz ochoty na iterację, spróbuj FBFriendModel.find({ id:333 }).remove( callback ); LUB FBFriendModel.find({ id:333 }).remove().exec();

mongoose.model.find zwraca zapytanie , które ma remove function .

 446
Author: Yusuf X,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-02-13 16:54:58

Począwszy od "mongoose": ">=2.7.1" możesz usunąć dokument bezpośrednio metodą .remove(), zamiast znajdować dokument, a następnie go usuwać, co wydaje mi się bardziej efektywne i łatwe w utrzymaniu.

Zobacz przykład:

Model.remove({ _id: req.body.id }, function(err) {
    if (!err) {
            message.type = 'notification!';
    }
    else {
            message.type = 'error';
    }
});

UPDATE:

Od mangusty 3.8.1 Istnieje kilka metod, które pozwalają bezpośrednio usunąć dokument, powiedzmy:

  • remove
  • findByIdAndRemove
  • findOneAndRemove

Zobacz mongoose API docs aby uzyskać więcej informacji informacje.

 263
Author: diosney,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-02 14:24:27

docs jest szereg dokumentów. więc nie ma metody mongooseModel.remove().

Można iterować i usuwać każdy dokument z tablicy oddzielnie.

Lub - ponieważ wygląda na to, że znajdujesz dokumenty za pomocą (prawdopodobnie) unikalnego identyfikatora-użyj findOne zamiast find.

 43
Author: mtkopone,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-01-24 09:30:33

To dla mnie najlepsze od wersji 3.8.1:

MyModel.findOneAndRemove({field: 'newValue'}, function(err){...});

I wymaga tylko jednego wywołania DB. Użyj tego, ponieważ nie wykonujesz żadnych remove działań pior do wyszukiwania i usuwania.

 35
Author: José Pinto,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-12-16 00:37:52

Po prostu zrób

FBFriendModel.remove().exec();
 30
Author: Sandro Munda,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-24 22:15:55

mongoose.model.find() zwraca obiekt zapytania , który ma również funkcję remove().

Możesz również użyć mongoose.model.findOne(), jeśli chcesz usunąć tylko jeden unikalny dokument.

W przeciwnym razie możesz zastosować tradycyjne podejście również tam, gdzie najpierw pobierasz dokument, a następnie usuwasz.

yourModelObj.findById(id, function (err, doc) {
    if (err) {
        // handle error
    }

    doc.remove(callback); //Removes the document
})

Poniżej znajdują się sposoby na model obiekt można wykonać jedną z następujących czynności, aby usunąć dokument(y):

yourModelObj.findOneAndRemove(conditions, options, callback)

yourModelObj.findByIdAndRemove(id, options, callback)

yourModelObj.remove(conditions, callback);

var query = Comment.remove({ _id: id });
query.exec();
 26
Author: Amol M Kulkarni,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-24 22:18:19

Do uogólnienia można użyć:

SomeModel.find( $where, function(err,docs){
  if (err) return console.log(err);
  if (!docs || !Array.isArray(docs) || docs.length === 0) 
    return console.log('no docs found');
  docs.forEach( function (doc) {
    doc.remove();
  });
});

Innym sposobem osiągnięcia tego jest:

SomeModel.collection.remove( function (err) {
  if (err) throw err;
  // collection is now empty but not deleted
});
 17
Author: alexandru.topliceanu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-07-04 14:52:16

Uważaj z findOne i usunąć!

  User.findOne({name: 'Alice'}).remove().exec();

Powyższy kod usuwa wszystkich użytkowników o imieniu "Alice" zamiast tylko pierwszego.

przy okazji, wolę usuwać takie dokumenty:

  User.remove({...}).exec();

lub dostarczyć wywołanie zwrotne i pominąć exec()

  User.remove({...}, callback);
 17
Author: damphat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-19 08:34:46
model.remove({title:'danish'}, function(err){
    if(err) throw err;
});

Ref: http://mongoosejs.com/docs/api.html#model_Model.remove

 14
Author: Danish,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-03-09 18:34:39

Jeśli szukasz tylko jednego obiektu do usunięcia, możesz użyć

Person.findOne({_id: req.params.id}, function (error, person){
        console.log("This object will get deleted " + person);
        person.remove();

    });

W tym przykładzie Mangusta usunie na podstawie dopasowania req.params.id.

 10
Author: bhavsac,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-10 22:31:15

.remove() działa jak .find():

MyModel.remove({search: criteria}, function() {
    // removed.
});
 9
Author: trusktr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-03-23 18:46:39

Wolę notację obietnicy, gdzie potrzebujesz np.

Model.findOneAndRemove({_id:id})
    .then( doc => .... )
 7
Author: Simon H,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-27 16:23:34

Do usuwania dokumentu wolę używać Model.remove(conditions, [callback])

Proszę zapoznać się z dokumentacją API do usunięcia:-

Http://mongoosejs.com/docs/api.html#model_Model.remove

W tym przypadku kod będzie:-

FBFriendModel.remove({ id : 333 }, function(err, callback){
console.log(‘Do Stuff’);
})

Jeśli chcesz usunąć dokumenty bez czekania na odpowiedź z MongoDB, nie przepuść połączenia zwrotnego, następnie musisz zadzwonić do exec na zwrócone zapytanie

var removeQuery = FBFriendModel.remove({id : 333 });
removeQuery.exec();
 7
Author: satyam kumar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-27 04:39:12

Możesz użyć zapytania bezpośrednio w funkcji Usuń, więc:

FBFriendModel.remove({ id: 333}, function(err){});
 6
Author: Charminbear,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-08-01 11:27:00

Zawsze możesz użyć wbudowanej funkcji mangusty:

var id = req.params.friendId; //here you pass the id
    FBFriendModel
   .findByIdAndRemove(id)
   .exec()
   .then(function(doc) {
       return doc;
    }).catch(function(error) {
       throw error;
    });
 4
Author: Doron Segal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-17 22:13:21

Działa dla każdej wersji mangusty, której użyłem

YourSchema.remove({
    foo: req.params.foo
}, function(err, _) {
    if (err) return res.send(err)
    res.json({
        message: `deleted ${ req.params.foo }`
    })
});
 4
Author: Joshua Michael Calafell,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-15 22:29:48

Używając metody remove () możesz usunąć.

getLogout(data){
        return this.sessionModel
        .remove({session_id: data.sid})
        .exec()
        .then(data =>{
            return "signup successfully"
        })
    }
 2
Author: KARTHIKEYAN.A,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 19:09:06

U mnie to zadziałało, po prostu spróbuj:

const id = req.params.id;
      YourSchema
      .remove({_id: id})
      .exec()
      .then(result => {
        res.status(200).json({
          message: 'deleted',
          request: {
            type: 'POST',
            url: 'http://localhost:3000/yourroutes/'
          }
        })
      })
      .catch(err => {
        res.status(500).json({
          error: err
        })
      });
 0
Author: MEAbid,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-30 11:47:59