Reputation: 6002
I have one endpoint in my api, which deletes one specific document:
exports.removeProduct = (req, res) => {
const productId = req.params.productId
Product.deleteOne({ _id: productId }, (err) => {
// handle response
})
}
Since the deleted document isn't in the database anymore, it should have been deleted at this point. Nevertheless, I retrieve the deleted document when calling this:
exports.getUnpublished = (req, res) => {
var unpublishedProducts = []
const userId = req.params.userId
Product.find({ userId: userId, published: false }, (err, products) => {
products.forEach((product) => {
if (Number(product.createdAt) === Number(product.updatedAt)) {
Product.remove({ _id: product._id }).exec();
} else {
unpublishedProducts.push(product)
}
})
// handle response
})
}
For explanation: First I find all documents that have the specific userId
and aren't yet published
. Afterwards, I loop over all of the found documents and remove all, that have never been updated. All other documents get pushed into the unpublishedProducts
array.
Oddly enough, the unpublishedProducts
array contains documents that have already been deleted.
P.S.: I noticed, that after restarting the server, the deleted documents aren't in the unpublishedProducts
array anymore.
Upvotes: 0
Views: 1223
Reputation: 618
You can update your product schema by adding a deleted: {type: Boolean, default: false}
attribute.
On the removeProduct
you can use
Product.updateOne({ _id: productId }, {$set: {deleted: true}}, (result) => {
// handle response
})
to retrieve all undeleted product you can use this query Product.find({deleted: {$ne: true}})
Upvotes: 2