0

There is a person Michael who has favoriteFruits = [ { name: 'Apple'}, {name: 'Banana'} ]

What I want to do is changing its order

[ { name: 'Apple'}, {name: 'Banana'} ]

to

[ { name: 'Banana'}, {name: 'Apple'} ]

So I did :

Members.findOne({ name: 'Michael' }, function(err, member){
    member.favoriteFruits = [ {name: 'Banana'}, {name: 'Apple'} ]

    member.save(function (err, result){

        // result is favoriteFruits = [ { name: 'Banana'}, {name: 'Apple'} ]
        // result is correct, but real db's order not changed.

    })
})

Even result's order of favoriteFruits is correct, but the order of db is not changed. The order is not changed.

I guess MongoDB assume this job is useless task so it doesn't do anything. How can I update order?

9
  • Array should preserve the order. Commented Oct 1, 2018 at 11:23
  • Apart from the result issue, why you are not using findOneAndUpdate instead of two separate queries? Commented Oct 1, 2018 at 11:30
  • @AnkitAgarwal So is there a way to accomplish it? Commented Oct 1, 2018 at 11:31
  • @Ved Sometimes I use, sometimes not. Especially when I have to handle something with queried data. Commented Oct 1, 2018 at 11:32
  • @AnkitAgarwal Perhaps should I add another key value pair such as [{ name: 'Banana', index: 0, { name: 'Apple', index: 1 }] and order by index...? I hope there will be more simple way.... Commented Oct 1, 2018 at 11:41

1 Answer 1

0

Most likely Mongoose is not noticing the difference between the arrays. You can tell Mongoose that the field has actually been modified by using the Document.prototype.markModified() method.

For your example:

Members.findOne({ name: 'Michael' }, function(err, member) {
    member.favoriteFruits = [{ name: 'Banana' }, { name: 'Apple' }];
    member.markModified('favoriteFruits');

    member.save(function (err, result) {

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

Comments

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.