Back to Freecodecamp

Delete Many Documents with model.remove()

curriculum/challenges/english/blocks/mongodb-and-mongoose/587d7fb8367417b2b2512c11.md

latest1.3 KB
Original Source

--description--

Model.remove() is useful to delete all the documents matching given criteria.

--instructions--

Modify the removeManyPeople function to delete all the people whose name is within the variable nameToRemove, using Model.remove(). Pass it to a query document with the name field set, and a callback.

Note: The Model.remove() doesn’t return the deleted document, but a JSON object containing the outcome of the operation, and the number of items affected. Don’t forget to pass it to the done() callback, since we use it in tests.

--hints--

Deleting many items at once should succeed

js
  const response = await fetch(code + '/_api/remove-many-people', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify([
      { name: 'Mary', age: 16, favoriteFoods: ['lollipop'] },
      { name: 'Mary', age: 21, favoriteFoods: ['steak'] }
    ])
  });
  if (!response.ok) {
    throw new Error(await response.text());
  }
  const data = await response.json();
  assert.isTrue(!!data.ok, 'The mongo stats are not what expected');
  assert.equal(
    data.n,
    2,
    'The number of items affected is not what expected'
  );
  assert.equal(data.count, 0, 'the db items count is not what expected');