node.js - 以后如何更改猫鼬模式的键?
问题描述
我有这样的架构
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 }
);
推荐阅读
- playwright-python - 在剧作家 python 中解决拖放问题
- spring - 使用 2 个表 Spring Security 进行身份验证
- reactjs - 处理自定义 SWR 挂钩中的错误
- c# - 如何在 c# 中将字符串值从一种形式传递到另一种形式?
- flask - 如何创建与 flask_socketio 和 telebot 的聊天?
- python - Tensorflow 2D 矩阵乘法返回矩阵产品列表
- python - 我可以抓取网站以识别其下的标题和文本吗?
- c - 我应该缩写库中的变量和函数名称吗?
- typescript - `import type` 是否等同于 `import()`
- c# - 如何将编译器生成的代码转换为可编译的 C# 代码