【问题标题】:How do I change the key of mongoose schema later?以后如何更改猫鼬模式的键?
【发布时间】:2021-12-25 21:47:28
【问题描述】:

我有这样的架构

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

请帮助我如何做到这一点。

【问题讨论】:

  • 只看你最后一段代码 - 分配不应该反过来吗?
  • 您能说得更准确些吗?我不明白你的意思。
  • 没关系,是我没有做研究,对不起。看看这里,它涵盖了你的问题:) docs.mongodb.com/manual/reference/operator/update/rename
  • 我猜它应该是 v["definition"] =v["defination"] 因为我想要带有“definition”的新键并且它们的值来自“definition”。我在这里找到它stackoverflow.com/questions/4647817/…。感谢您的文档链接。我会读的。

标签: node.js database mongodb mongoose mongoose-schema


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-26
    • 2019-11-06
    • 2023-03-04
    • 2016-08-05
    • 1970-01-01
    • 2020-05-18
    • 2014-04-01
    相关资源
    最近更新 更多