如何使用猫鼬在另一个模型中引用一个模型?



我对节点和猫鼬很陌生,还在学习很多东西。基本上我试图创建一个论坛页面。我有一个论坛模式,我最近添加了一个新的字段,我想显示哪个用户发布了它。我在网上读过其他问题,我能够遵循那里的代码,但我的仍然不工作。当我检查我的数据在地图集它仍然缺少新的"提交"字段,我添加。我已经删除了"集合"并重新开始,但它仍然缺失。任何帮助都会很感激。下面是我的模型,以及如何将数据发布到数据库的屏幕截图。

**Post Form Schema** 
const mongoose = require('mongoose');
const PostSchema = new mongoose.Schema({
title: {
type: String,
required: true
},
body: {
type: String,
required: true,
},
date: {
type: Date,
default: Date.now,
required: true,
},
submittedBy: { *(this is where I would like to get the user who submitted the form)*
type: mongoose.Schema.Types.ObjectId, 
ref: 'User',
},
extraInfo: {
type: String,
default: 'Other info goes here',
}
})
const Post = mongoose.model('Post', PostSchema);
module.exports = Post;
**Users Form Schema**
const mongoose = require('mongoose');
const UserSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
});
const User = mongoose.model('User', UserSchema);
module.exports = User;

编辑:这是我的新帖子路由


const express = require('express');
const Post = require('../models/post');
const router = express.Router();
const {ensureAuthenticated} = require("../config/auth.js");
router.get('/', ensureAuthenticated, (req, res) => {
res.render('newPost')
})
router.post('/', ensureAuthenticated, (req, res) => {
const post = new Post(req.body);
console.log(req.body)
post.save()
.then((result) => {
res.redirect('/dashboard')
})
.catch((err) => {
console.log(err)
})
})
module.exports = router;

如果我没弄错的话,您可以使用"ensureAuthenticated"验证它是否经过身份验证。中间件(用户ID应该在那里),但是当创建"Post"您只能对body数据执行此操作。

就像这样(你应该替换"userId"与您的属性名称):

const post = new Post({ ...req.body, submittedBy: userId })

最新更新