0

I am trying to remove all the elements from the array in the MongoDB database, then I insert all the new array elements.

My Model is:

 const mongoose = require('mongoose');
var schema = new mongoose.Schema({
    email : {
        type : String
    },
    password : {
        type : String
    },
    stocks : {
        type : [String]
    }
}, {versionKey:false}, {_id: false});
module.exports =  final = mongoose.model('users', schema);

My stocks array will then have some values. I am trying to remove those values using the following command: I read at somewhere in Stack Overflow that to empty your array you can do many things but a set is the fastest way to do this. Please let me know if you know any other way which is better than this.

final
  .findOneAndUpdate({email:"abcd@gmail.com"}, {$set:{stocks:[]}})
  .then(()=>console.log("Data removed."))
  .catch(err=>console.log(err));

Once data is removed it means the array will get emptied. Then I assign the whole set of the new array from my local variable like this:

const newData = {
  stocks : ["abcd", "wxyz"]
};

Now I am trying to assign this new array to my database using this command:

final
  .findOneAndUpdate({email:"abcd@gmail.com"}, {$set:{stocks:newData.stocks}});

It is emptying the array successfully, but when I am assigning new array it is not working and shows an empty array. Can anyone assist me with this, please?

Yash Choksi
  • 2,132
  • 3
  • 9
  • 18
  • This does not reproduce, aside from a possible misuse of `final` where you meant `Pref` as the model. Basically appears to be a typo with no other cause. – Neil Lunn Mar 19 '19 at 08:43
  • Please check edited question... Actually it's typo but there must be something other issue... – Yash Choksi Mar 19 '19 at 08:44
  • Argh! You're looking at the old document. Duplicate of [Mongoose: findOneAndUpdate doesn't return updated document](https://stackoverflow.com/questions/32811510/mongoose-findoneandupdate-doesnt-return-updated-document). Missing `{ new: true }` – Neil Lunn Mar 19 '19 at 08:45
  • @NeilLunn Thanks bro, I got your point and I solved it. – Yash Choksi Mar 19 '19 at 08:53

1 Answers1

1

Try with

final.findOneAndUpdate({email:"abcd@gmail.com"}, {$set:{stocks:newData.stocks}}, {new: true})
    .then((doc)=>console.log(doc))
    .catch(err=>console.log(err));

If you don't use a callback the query is not executed.

The query executes if callback is passed else a Query object is returned. Mongoose documentation

Simone Morettini
  • 371
  • 2
  • 12