【问题标题】:how to reference a model in another model using mongoose?如何使用猫鼬引用另一个模型中的模型?
【发布时间】:2021-05-24 06:24:12
【问题描述】:

我对 node 和 mongoose 还是很陌生,仍然学到很多东西。基本上我正在尝试创建一个论坛页面。我有一个论坛帖子架构,我最近添加了一个新字段,我想显示哪个用户发布了它。我已经在网上阅读了其他问题,并且能够按照那里的代码进行操作,但是我的仍然无法正常工作。当我在 atlas 中检查我的数据时,它仍然缺少我添加的新的“提交者”字段。我已经删除了“收藏”并重新开始,但它仍然丢失。任何帮助,将不胜感激。下面是我的模型以及如何将数据发布到数据库的屏幕截图。

**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;

【问题讨论】:

    标签: node.js mongodb mongoose schema


    【解决方案1】:

    如果我没记错的话,您可以验证是否使用“ensureAuthenticated”中间件进行了身份验证(用户 ID 应该在那里),但是在创建“帖子”时,您只需要使用正文数据。

    是这样的(你应该用你的属性名称替换“userId”):

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

    【讨论】:

    • 感谢您的回复!这是我的“新帖子”路线
    • 我根据您告诉我的更改编辑了答案!
    • 你是一个救星,出于某种原因,我认为它会自动拉用户提交,忽略了我必须分配它的事实。谢谢!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-13
    • 2021-08-17
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多