Dealing with schema changes in Mongoose

后端 未结 3 1431
轻奢々
轻奢々 2020-11-30 22:37

What\'s the best practice (or tool) for updating/migrating Mongoose schemas as the application evolves?

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-30 22:54

    I just had this problem where I needed to update my database to reflect the changes to my schema. After some research I decided to try the updateMany() function in the mongo console to make the updates and I think it worked pretty well.

    To apply this to vimdude's example the code would look as follows:

    try { 
        db..updateMany( { birthplace: null }, { $set: 
                  {"birthplace": "neverborn" } } ); 
    } catch(e) { 
        print(e);
    }
    

    The updateMany() function will update all documents in a collection based on a filter. In this case the filter is looking for all documents where the field 'birthplace' is null. It then sets a new field in those documents named 'birthplace' and sets its value to 'neverborn'.

    After running the code, modified to reflect your circumstances run:

    db..find().pretty()
    

    to verify that the changes were made. The new field "birthplace" with the value of "neverborn" should show at the end of each document in your collection.

    Hope that helps.

提交回复
热议问题