【发布时间】: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