I just had a quick question about a problem I have been running into with MongoDB using Node.js. I am not able to delete all the documents in a collection using the command "db.users.remove({})". I know that the collection name is correct. I have run this in the terminal and although it seems as though the command was run, it did not delete all the documents in the collection. When I run it using a post request, it just says db is not defined, which makes no sense to me. The reason why I have no query string is that I want to delete all the documents. I have included all my code below, but if a person can tell me perhaps a better way to delete all the documents in a collection or a solution to my problem I will greatly appreciate it. Thanks!
const fs = require('fs')
const express = require('express')
const router = express.Router()
const checkTypes = require('checktypes-js')
const schema = require('../schemas/user')
const usersDB = require('../models/usersModel')
const { Types } = require('mongoose')
const fileQuery = "logs.txt"
router.post('/new', (req, res) => {
checkTypes(req.body, schema.user, async (err, passedObject) => {
if (err){
console.log(err)
return res.json({errors: err})
} else {
const existingUserEmail = await usersDB.findOne({email: passedObject.email})
const existingUserUsername = await usersDB.findOne({username: passedObject.username})
console.log(existingUserEmail, existingUserUsername)
if (existingUserEmail || existingUserUsername){
return res.json({error: "A user with that email or username exists too!"})
}
passedObject.active = true
const addedUser = await usersDB.create(passedObject)
res.send(addedUser)
const fileMessage = "\nNew user with username of " + existingUserUsername + ' has been added on ' + new Date()
console.log(fileMessage)
return fs.appendFile(fileQuery, fileMessage, function (err){
if (err){
console.error(err)
}
res.send("The file has been successfully written to!")
})
}
})
})
router.post('/update', (req, res) => {
checkTypes(req.body, schema.user, async (err, passedObject) => {
if (err){
console.log(err)
return res.json({errors: err})
} else {
const {_id, ...update} = passedObject
if(!Types.ObjectId.isValid(_id)){
return res.json({error: 'Invalid id supplied'})
}
const updatedUser = await usersDB.findByIdAndUpdate(_id, update, {new: true})
if (!updatedUser){
return res.json({error: "Could not find the user with that ID!"})
} else {
res.json(updatedUser)
const fileMessage = "\nUpdate user with id of " + _id + ' on ' + new Date()
console.log(fileMessage)
return fs.appendFile(fileQuery, fileMessage, function (err){
if (err){
console.error(err)
}
res.send("The file has been successfully written to!")
})
}
}
})
})
router.post("/delete", (req, res) => {
checkTypes(req.body, schema.user, async (err, passedObject) => {
if (err){
console.log(err)
res.json({error: err})
} else {
const {_id, ...deleteObj} = passedObject
console.log(_id)
if(!Types.ObjectId.isValid(_id)){
return res.json({error: 'Invalid id supplied'})
}
const deleteUser = usersDB.findByIdAndRemove({_id: _id}, function (err){
if (err){
return res.send("A user with that ID is not defined!")
} else {
res.send("The object has been deleted!")
const fileMessage = "\nUser with id of " + _id + ' has been delete on ' + new Date()
console.log(fileMessage)
return fs.appendFile(fileQuery, fileMessage, function (err){
if (err){
console.error(err)
}
res.send("The file has been successfully written to!")
})
}
})
}
})
})
router.post("/deleteAll", (req, res) => {
db.users.remove({})
res.send("All documents have been deleted!")
const fileMessage = "\nAll documents in the remindars collection have been deleted on " + new Date()
console.log(fileMessage)
return fs.appendFile(fileQuery, fileMessage, function (err){
if (err){
console.error(err)
}
res.send("The file has been successfully written to!")
})
})
router.post('/testFile', (req, res) => {
const fileMessage = "\nThe file writing script was tested on " + new Date()
console.log(fileMessage)
return fs.appendFile(fileQuery, fileMessage, function (err){
if (err){
console.error(err)
}
res.send("The file has been successfully written to!")
})
})
router.post('/clearFile', (req, res) => {
const fileMessage = ""
console.log(fileMessage)
return fs.writeFile(fileQuery, fileMessage, function (err){
if (err){
console.error(err)
}
res.send("The file has been successfully written to!")
})
})
module.exports = router
dbvariable anywhere in your code :) Butdb.[collection].remove({})in the Mongo Shell should totally work.usersDB.remove({}, callback)db.users.remove({})is asynchronous, and needs to be exec'd to get a promise that you can await if you don't provide a callback. Follow Akrion's answer to await the remove operation, especially before writing outres.send("All documents have been deleted!")because it just isn't true yet, until you await the promise.