marcvander
marcvander

Reputation: 647

Deleting values in array (MongoDB and mongoose)

I have a collection. In this collection I have only one document like this:

_id:
emails: []

I would like to delete the values in emails array.

My code under /models/askForReferral.js:

const mongoose = require('mongoose');

const WaitingForReferral = mongoose.model('WaitingForReferral', new mongoose.Schema({

    emails: []

}));

exports.WaitingForReferral = WaitingForReferral;

My code under /routes/referralEmail.js:

const { WaitingForReferral } = require('../models/askForReferral');
const express = require('express');
const router = express.Router();

router.post('/', async (req, res) => {

    WaitingForReferral.update(
        { },
        { $unset: { emails: "" } }
     )

});

When I run my code, it runs without error, but emails array is not emptied.

Any idea?

Upvotes: 1

Views: 25

Answers (1)

Ashh
Ashh

Reputation: 46491

Use $set operator with blank array [] and also mongoose query returns promise you need to use await to execute it

await WaitingForReferral.update(
  { },
  { $set: { emails: [] } }
)

Upvotes: 1

Related Questions