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:"[email protected]"}, {$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:"[email protected]"}, {$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?

4
  • 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. Commented Mar 19, 2019 at 8:43
  • Please check edited question... Actually it's typo but there must be something other issue... Commented Mar 19, 2019 at 8:44
  • Argh! You're looking at the old document. Duplicate of Mongoose: findOneAndUpdate doesn't return updated document. Missing { new: true } Commented Mar 19, 2019 at 8:45
  • @NeilLunn Thanks bro, I got your point and I solved it. Commented Mar 19, 2019 at 8:53

1 Answer 1

1

Try with

final.findOneAndUpdate({email:"[email protected]"}, {$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

Sign up to request clarification or add additional context in comments.

1 Comment

I edited the answer. The problem is that you miss the callback

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.