【问题标题】:mongoose doesn't update a default state猫鼬不更新默认状态
【发布时间】:2022-07-29 15:50:47
【问题描述】:

嗨,我有一个具有默认状态的帖子架构,我只想在创建新帖子时更新默认状态,但我的代码没有为此更新 它不会同时更新和保存新帖子

这是我的帖子架构

const postSchema = mongoose.Schema({
  title: String,
  message: String,
  name: String,
  tags: [String],
  picture: String,
  likes: {
    type: [String],
    default: [],
  },
  createdAt: {
    type: Date,
    default: Date.now(), //problem here 
  },
  profilePicture: String,
  userId: String,
  comments: {
    type: [
      {
        commentUserId: String,
        commentUserName: String,
        comment: String,
        createdAt: Date,
      },
    ],
  },
});
export const createPost = async (req, res) => {
  const post = req.body;
  const newPost = new Post({ ...post, createAt: new Date() }); // I update it but doesn't work 
  try {
    await newPost.save();
    const user = await User.findById(post.userId);
    user.userPosts.unshift(newPost);
    await user.save();
    res.status(201).json(newPost);
  } catch (error) {
    res.status(404).json({ message: error.message });
  }
};

【问题讨论】:

    标签: javascript node.js mongoose


    【解决方案1】:

    请在发布到堆栈溢出之前检查拼写错误。 在您的架构中,您已将密钥命名为 createdAt。在您的新 mongoose 对象中,您已将其命名为 createAt。 (注意缺少的“d”)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-05
      • 2016-06-20
      • 2020-11-13
      • 2012-03-28
      • 2016-05-24
      • 1970-01-01
      • 2012-12-21
      • 2018-10-02
      相关资源
      最近更新 更多