以后如何更改mongoose模式的密钥



我有一个类似的模式

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" },
});

看看";定义";钥匙拼写不正确。我想把它改回";定义";。但问题是,有很多文件添加了";定义";。我如何将它们改回";定义";?

为了更清楚,我在这些数据中添加了关键字";定义";。它们如下

[
{
_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
}
]

我想把钥匙换成";定义";至";定义";在这些现有文件中。这是我迄今为止尝试过的,但没有成功。

Vocabulary.find({}).then((voca) => {
voca.forEach((v) => {
v["definition"] = v["defination"];
console.log(v);
});
});

请帮我怎么做。

您可以使用$rename运算符。首先筛选所有具有defination字段的文档,然后为所有这些文档重命名该字段。

Vocabulary.update(
{ defination: { $exists: true } },
{ $rename: { "defination": "definition" } },
{ upsert: false, multi: true  }
);

最新更新