0

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
4
  • Well, the code usually doesn't lie, and it's the same in your case. You don't have db variable anywhere in your code :) But db.[collection].remove({}) in the Mongo Shell should totally work. Commented Nov 5, 2018 at 15:51
  • seeing the first method, this should delete all users: usersDB.remove({}, callback) Commented Nov 5, 2018 at 15:54
  • Wait so do I exactly type "db.[collection].remove({})" in the mongo shell? Or do I replace "[collection]" with the name of my collection, which is "users". If I do have to replace it, then that is exactly what I did in the mongo shell before but it didn't work. I typed in "db.users.remove({})". Commented Nov 5, 2018 at 15:56
  • 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 out res.send("All documents have been deleted!") because it just isn't true yet, until you await the promise. Commented Nov 5, 2018 at 16:36

1 Answer 1

1

You have:

const usersDB = require('../models/usersModel')

Which is your mongoose model but you are calling db.users.remove({}).

Use your model like everywhere else in your code:

const result = await usersDB.remove({}).exec()

or:

Author.remove({}).then(x => {
  console.log(x)
})
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Have a great day!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.