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?

ton1
  • 7,238
  • 18
  • 71
  • 126
  • Array should preserve the order. – Ankit Agarwal Oct 01 '18 at 11:23
  • Apart from the result issue, why you are not using `findOneAndUpdate ` instead of two separate queries? – Ved Oct 01 '18 at 11:30
  • @AnkitAgarwal So is there a way to accomplish it? – ton1 Oct 01 '18 at 11:31
  • @Ved Sometimes I use, sometimes not. Especially when I have to handle something with queried data. – ton1 Oct 01 '18 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.... – ton1 Oct 01 '18 at 11:41
  • It's probably not mongodb but mongoose that is not handling the update correctly. try this: `member.markModified('favoriteFruits');` before saving. – nijm Oct 01 '18 at 13:23
  • Possible duplicate of https://stackoverflow.com/questions/35810951/how-to-change-order-of-array-with-mongodb – chridam Oct 01 '18 at 13:56
  • @chridam it's not a duplicate, he is asking for Mongoose specifically and it's a problem with Mongoose specifically. – nijm Oct 02 '18 at 11:02
  • @nijm I know that's why I said "possible" because you can use the same concepts in MongoDB – chridam Oct 02 '18 at 11:04

1 Answers1

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) {

    });
});
nijm
  • 2,158
  • 12
  • 28