Home > Blockchain >  mongoose doesn't update a default state
mongoose doesn't update a default state

Time:07-29

hi I have a post schema that has a default state I just want to update a default state when it creates a new post but my code doesn't update for that it doesn't update and save a new post with the same time

here's my schema of post

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

CodePudding user response:

Kindly check for typos before posting to stack overflow. In your schema, you've named your key createdAt. In your new mongoose object, you've named it createAt. ( notice the missing "d" )

  • Related