'How to make all of the documents in a collection the same?
I would like to know how I can make all the documents in a collection the same, to avoid errors like for example: a value does not exist in an old document but in other new documents it does.
Example:
Imagine we have a database, a collection, and there are two documents in that collection:
- MyDatabase
- MainCollections
- {
"name": "Sandy",
"hobbies": "Programming"
},
- {
"name": "Xavier",
"hobbies": "Playing"
}
Then, the schema of that collection would be like this:
import { Schema, model } from "mongoose";
const mainCollectionSchema: Schema = new Schema({
name: {
type: String,
required: true
},
hobbies: {
type: String,
required: true
}
})
exports default model("mainCollection", mainCollectionSchema);
But here comes the problem, what if I add an update to my application, and change the schema to this:
import { Schema, model } from "mongoose";
const mainCollectionSchema: Schema = new Schema({
name: {
type: String,
required: true
},
hobbies: {
type: String,
required: true
},
friends: {
type: [String],
required: false,
default: []
}
})
exports default model("mainCollection", mainCollectionSchema);
Then, only new users will be able to have this feature since their document is being created through the new model, while "Sandy" and "Xavier" will not have the "friends" key in their document since it was the old one.
Now, the question, how can I update all the documents in a collection to follow a specific model in order to make all of the documents the same?
Just for example, here's how it would look:
- MyDatabase
- MainCollections
- {
"name": "Sandy",
"hobbies": "Programming"
},
- {
"name": "Xavier",
"hobbies": "Playing"
},
- {
"name": "Sara",
"hobbies": "Sing",
"friends": [
"Sandy"
]
}
And here's how I want it to be:
- MyDatabase
- MainCollections
- {
"name": "Sandy",
"hobbies": "Programming",
"friends": [
"Sara"
]
},
- {
"name": "Xavier",
"hobbies": "Playing",
"friends": []
},
- {
"name": "Sara",
"hobbies": "Sing",
"friends": [
"Sandy"
]
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
