我正在使用 node.js 和 mongoDB 创建一个基本的社交媒体 Web 应用程序。我在创建帖子时遇到问题。我不断收到上面给出的错误,并且它不断指向模型 post.js 第 3:20 行。
postController.js
const Post = require('../models/post')
const createPost = async (req, res) => {
try {
const {media} = req.body;
const newPost = new Post({
media: media,
user: req.userId
})
await newPost.save();
res.status(201).json(newPost);
} catch (error) {
console.log(error);
res.status(500).json({message: "something went wrong"});
}
}
module.exports = createPost;
post.js
const mongoose = require('mongoose');
const postSchema = new mongoose.Schema({
media: {
type: String,
trim: true,
required: true
},
user: {
type: mongoose.Schema.Types.objectId,
ref: "User",
},
likes: [
{
type: mongoose.Schema.Types.objectId,
ref: "Like"
}
],
comment: [
{
type: mongoose.Schema.Types.objectId,
ref: "Comment"
}
]
},{
timestamps: true,
});
mongoose.export = mongoose.model("Post", postSchema);
post.js(路由/api)
const express = require('express');
const createPost = require('../../controllers/postController');
const auth = require('./middleware/auth');
const postRouter = express.Router();
postRouter.get("/", auth, getPost);
postRouter.post("/", auth, createPost);
postRouter.delete("/:postID", auth, deletePost);
module.exports = postRouter;
我无法找出我做错了什么。请帮忙。
您有一个拼写错误,
ObjectId
必须以大写字母开头。mongoose.Schema.Types.ObjectId