首页 > 解决方案 > 在我的 nodejs 应用程序中有两个单独的模式

问题描述

对javascript来说相当新,我正在尝试将我的Web应用程序上的输入表单中的数据保存到我的mongodb集群中。我已经为我的应用程序创建了一个登录和注册表单,它成功保存在我的mongodb集群中,我的架构如下:(ps我添加projecttitle: {type: mongoose.Schema.Types.ObjectId,ref: "Project"}到该架构中以尝试与其他架构链接,不知道是否是正确的?)

const mongoose = require('mongoose');

const UserSchema = new mongoose.Schema({
    username: {
        type: String,
        required: true
    },
    password: {
        type: String,
        required: true
    },
    emailaddress: {
        type: String,
        required: true
    },
    projecttitle: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "Project"
    }
});


const User = mongoose.model('User', UserSchema,);

module.exports = User;

但是,一旦用户登录,他们就会遇到具有不同输入的不同输入表单。我还想将该输入数据保存在我的 mongoDB图集集合中,并将表单中的输入数据与输入它的用户相关联。我想保存数据,这样当用户重新登录到他们的帐户时,我最终可以在主页上显示他们之前在该表单中输入的数据。我使用了这个模式:(我添加了 ps postedBy: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},尝试将这个模式与 UserSchema 关联起来,我不知道这是否正确)

const mongoose = require('mongoose');

const ProjectSchema = new mongoose.Schema({
    postedBy: {
        type: mongoose.Schema.Types.ObjectId, ref: 'User'},
    projecttitle: {
        type: String,required: true},
    projectmodule: {
        type: String,required: true},
    dateone: {
        type: Date,required: true},
    datetwo: {
        type: Date,required: true},
    milestones: {
        type: String,required: true}
});


const Project = mongoose.model('Project', ProjectSchema,);

module.exports = Project;

这是我的 app.js 文件的片段,用于尝试将 , 保存ProjectSchema到我的数据库中的集合中。

//homepage
router.get('/homepage', forwardAuthenticated, (req, res) => res.render('homepage'));

    router.post('/homepage', (req, res) => {
      const { projecttitle, projectdescription, dateone, datetwo, } = req.body;

      let errors = [];

      if (!projecttitle ||  !projectdescription|| !dateone || !datetwo ) {
        errors.push({ msg: 'Missing entries. Please fill in every field' });
      }

      if (errors.length > 0) {
        res.render('homepage', {
          errors,
          projecttitle,
          projectdescription,
          dateone,
          datetwo  
        });
      } else {

                const newProject = new Project({
                  projecttitle,
                  projectdescription,
                  dateone,
                  datetwo
                });
                newProject.save()
                .then(user => {
                  req.flash(
                    'good',
                    'You have now made a project and its saved in our system'
                  );
                  res.redirect('/users/homepage');
                })
              }})

道歉,如果这没有意义,任何帮助将不胜感激。如果您需要有关我的代码的更多信息,请告诉我。

标签: javascriptnode.jscluster-computingmongodb-atlas

解决方案


推荐阅读