I have a schema like this
const vocabularySchema = new mongoose.Schema({
vocabulary: { type: String, required: true },
defination: { type: String, required: true },
exampleSentences: [{ type: String }],
note: { type: String },
timeStamp: { type: Date, default: Date.now },
resource: { type: String },
owner: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
});
look at the "defination" key. The spelling is incorrect. I want to change it back to "definition". But the problem is there are a lot of documents added with "defination". How do I change them back to "definition"?
To be more clear, I have these data added with key "defination". They are as follow
[
{
_id: new ObjectId("618fe4f6ee433e36f0392785"),
vocabulary: 'destiny',
defination: 'the events that will necessarily happen to a particular person or thing in the future.',
exampleSentences: [ 'If something is our destiny, there is no way we can avoid it.' ],
note: '',
timeStamp: 2021-11-13T16:16:54.897Z,
resource: '',
owner: new ObjectId("6162e68db8d492f28b8e7870"),
__v: 0
}
{
_id: new ObjectId("618fe554ee433e36f0392795"),
vocabulary: 'rumor',
defination: 'a currently circulating story or report of uncertain or doubtful truth.',
exampleSentences: [ 'You should never be bothered by rumor s.' ],
note: '',
timeStamp: 2021-11-13T16:18:28.523Z,
resource: '',
owner: new ObjectId("6162e68db8d492f28b8e7870"),
__v: 0
}
]
I want to change the key "defination" to "definition" in these existing documents. This is what I have tried so far but didn't work.
Vocabulary.find({}).then((voca) => {
voca.forEach((v) => {
v["definition"] = v["defination"];
console.log(v);
});
});
Please help me with how to do that.
CodePudding user response:
You can use $rename operator. First filter all documents that have defination
field, and then rename that field for all these documents.
Vocabulary.update(
{ defination: { $exists: true } },
{ $rename: { "defination": "definition" } },
{ upsert: false, multi: true }
);