exercise 3 in MongoDB and Mongoose section
const removeOne = require("./myApp.js").removeById;
router.post("/remove-one-person", function (req, res, next) {
//change to Person.deleteOne()
Person.remove({}, function (err) {
if (err) {
return next(err);
}
let t = setTimeout(() => {
next({ message: "timeout" });
}, TIMEOUT);
let p = new Person(req.body);
p.save(function (err, pers) {
if (err) {
return next(err);
}
try {
removeOne(pers._id, function (err, data) {
clearTimeout(t);
if (err) {
return next(err);
}
if (!data) {
console.log("Missing `done()` argument");
return next({ message: "Missing callback argument" });
}
console.log(data);
Person.count(function (err, cnt) {
if (err) {
return next(err);
}
data = data.toObject();
data.count = cnt;
console.log(data);
res.json(data);
});
});
} catch (e) {
console.log(e);
return next(e);
}
});
});
});
const removeMany = require("./myApp.js").removeManyPeople;
router.post("/remove-many-people", function (req, res, next) {
//Change to Person.deleteMany()
Person.remove({}, function (err) {
if (err) {
return next(err);
}
let t = setTimeout(() => {
next({ message: "timeout" });
}, TIMEOUT);
Person.create(req.body, function (err, pers) {
if (err) {
return next(err);
}
try {
removeMany(function (err, data) {
clearTimeout(t);
if (err) {
return next(err);
}
if (!data) {
console.log("Missing `done()` argument");
return next({ message: "Missing callback argument" });
}
Person.count(function (err, cnt) {
if (err) {
return next(err);
}
if (data.ok === undefined) {
// for mongoose v4
try {
data = JSON.parse(data);
} catch (e) {
console.log(e);
return next(e);
}
}
res.json({
n: data.n,
count: cnt,
ok: data.ok,
});
});
});
} catch (e) {
console.log(e);
return next(e);
}
});
});
});
I believe Model.remove() needs to be changed to either Model.deleteOne() or Model.deleteMany(), with Model being Person in this case.