【问题标题】:How to add a modifier to a nested document with mongodb如何使用 mongodb 向嵌套文档添加修饰符
【发布时间】:2021-07-19 11:42:01
【问题描述】:

我有这个模型

  1. 这是模型
    const PostSchema = nongoose.Schema(
      {
    body: {
      type: String,
      trim: true,
      maxlength: 250,
      required: true,
    },
    comments: {
      required: true,
      type: [
        {
          creatorId: {
            type: String,
            required: true,
          },
          creator: {
            type: String,
            required: true,
          },
          timestamp: Number,
          body: {
            type: String,
            required: true,
            trim: true,
          },
          likes: {
            type: [String],
            required: true,
          },
          replies: {
            require: true,
            type: [
              {
                creatorId: String,
                creatorName: String,
                timestamp: Number,
                body: {
                  type: String,
                },
              },
            ],
          },
        },
      ],
    },
      },
      {
    timestamps: true,
      }
    );

我想在每次收到所有帖子时将 isReady= true 附加到每个 cmets。 基本上我不想将它添加到我的数据库中。

  1. 这是我的控制器
module.exports.readPost = async (req, res) => {
  await PostModel.find((err, doc) => {
    !err ? res.send(doc) : console.log("Get Data Error" + err);
  }).sort({ createdAt: -1 });
};

我想在每次收到所有帖子时将 isReady= true 附加到每个 cmets。 基本上我不想将它添加到我的数据库中。

【问题讨论】:

  • 不将其添加到您的收藏中,您的意思是不将其保存到数据库中吗?
  • 是的,我想从服务器上做

标签: reactjs mongodb express mongoose mongodb-query


【解决方案1】:

使用Mongoose Lean将doc转换为javascript对象,然后使用Array.map修改docs中的所有items

module.exports.readPost = async (req, res) => {
  try {
    const doc = await PostModel.find().lean();
    const sortedDoc = doc.sort({ createdAt: -1 });
    const modifiedDocs = sortedDoc.map((item) => {
      item.comments.isReady = true;
      return item;
    });

    res.send(modifiedDocs);
  } catch (error) {
    console.log('Get Data Error' + err);
  }
};

【讨论】:

  • 有没有办法用 mongo db 查询修饰符添加它 ¶
  • 你的意思是喜欢使用Mongoose吗?这可能会更改数据库中的文档? @DimerBwimba
  • 我的意思是像 db.collection.find( { } )._addSpecial(
  • 我不确定我理解你的意思。你是从 Mongoose 文档中得到这个 db.collection.find( { <query> } )._addSpecial( <option> ) 的吗? @DimerBwimba
  • 我想你可能是想使用Mongoose Lean
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-06-27
  • 1970-01-01
  • 1970-01-01
  • 2017-04-01
  • 2018-03-09
  • 1970-01-01
  • 2015-02-10
相关资源
最近更新 更多