使用提交按钮/输入标签将数据插入猫鼬模式

Posted

技术标签:

【中文标题】使用提交按钮/输入标签将数据插入猫鼬模式【英文标题】:Inserting data into mongoose Schema using submit button/input tag 【发布时间】:2021-10-07 21:23:25 【问题描述】:

所以我一直在开发一种电子商务网站,用户可以在其中为他们喜欢的商店添加书签,然后将其保存到数据库中。

我有两种猫鼬模式,一种用于商店,另一种用于用户

//jshint esversion:6
require('dotenv').config();
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const mongoose = require("mongoose");
const session = require("express-session");
const passport = require("passport");
const passportLocalMongoose = require("passport-local-mongoose");
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const findOrCreate = require("mongoose-findorcreate");
const cors = require("cors");


const app = express();

app.set('view engine', 'ejs');
// app.use(cors());
// app.use(express.json());
app.use(bodyParser.urlencoded(extended: true));
app.use(express.static("public"));


app.use(session(
  resave: false,
  saveUninitialized: true,
));


app.use(passport.initialize());
app.use(passport.session());


mongoose.connect('mongodb://localhost:27017/journalDB', useNewUrlParser: true, useUnifiedTopology: true);
mongoose.set('useCreateIndex', true);

const journalSchema = new mongoose.Schema(
  title: String,
  category: String,
  subcategory: String,
  rating: Number,
  link: String,
  description: String,
);

const userSchema = new mongoose.Schema (
  username: String,
  password: String,
  journal: [type: mongoose.Schema.Types.ObjectId, ref: 'Journal']
);


userSchema.plugin(passportLocalMongoose);
userSchema.plugin(findOrCreate);


const Journal = mongoose.model("Journal", journalSchema);
const User = mongoose.model("User", userSchema);

每个商店都有一个带有描述的单独页面。我想添加一个按钮或输入标签,这会将这家商店保存到用户的架构中。

获取和发布路线:

app.get("/journals/:journalId", function(req, res)
  const requestedJournalId = req.params.journalId;

  Journal.findOne(_id: requestedJournalId, function(err, foundJournal)
      res.render("stats", 
        _id: foundJournal._id,
        title: foundJournal.title,
        subcategory: foundJournal.subcategory,
        link: foundJournal.link,
        description: foundJournal.description
      );
  );
);

app.post("/stats", function(req, res)
    const favJournal = req.journal.id;
    User.findById(req.user.id, function(err, foundUser) 

        if (err) 
            console.log(err);
         else 
            if (foundUser) 
                foundUser.journal.push(favJournal);
                foundUser.save(function() 
                    res.redirect("/favourite");
                );
            
        
    );
);

stats.ejs:

<div class="container py-4">
  <div class="row">
    <div class="col">
      <div class="flex-container-stats">
        <div class="stats-image">
          <img class="img-fluid" style="height: 350px;max-wdth:500px;"  id="img_DocPreview" src="images/clothes.jfif" >
        </div>
        <div class="stats-description">
          <h1 class="display-5 fw-bold "><%=title%></h1>
          <p class="fs-4"><%=subcategory%></p>
          <a href="<%=link%>" target="_blank" ><i class="fab fa-instagram fa-3x"></i></a>
          <a href="https://www.facebook.com/" target="_blank" class="px-2"><i class="fab fa-facebook-square fa-3x"></i></a>
          <a href="https://telegram.org/" target="_blank" class="px-2"><i class="fab fa-telegram-plane fa-3x"></i></a>
        </div>
      </div>
        <form action="/stats" method="post">
          <div class="stats-button">
            <!-- <label for=""><%=_id%></label>
            <input type="submit" name="savedJournal" placeholder="Add to favourite"> -->
          </div>
        </form>
    </div>
  </div>
</div>

我是 MongoDB 和 node.js 的新手。不确定我缺少什么,也无法从遇到的类似问题中找到合适的解决方案。

【问题讨论】:

【参考方案1】:

将您的架构文件更改为类似于以下示例的内容:

const mongoose = require('mongoose');

const journalSchema = new mongoose.Schema(
    title: String,
    category: String,
    subcategory: String,
    rating: Number,
    link: String,
    description: String,
);

const userSchema = new mongoose.Schema(
    username: String,
    password: String,
    journal: [type: mongoose.Schema.Types.ObjectId, ref: 'Journal']
);

module.exports.userSchema = mongoose.model('users', userSchema);
module.exports.journalSchema = mongoose.model('journals', journalSchema);

然后,这会将您的架构转换为实时模型,从而允许您的数据实际保存在您的数据库中。 然后要求您的数据库使用以下示例:

const express = require('express');
const app = express();
const Journal = require('./path/to/schema-file').journalSchema;
const User = require('./path/to/schema-file').userSchema;

app.get("/journals/:journalId", function(req, res)
  const requestedJournalId = req.params.journalId;

  Journal.findOne(_id: requestedJournalId, function(err, foundJournal)
      res.render("stats", 
        _id: foundJournal._id,
        title: foundJournal.title,
        subcategory: foundJournal.subcategory,
        link: foundJournal.link,
        description: foundJournal.description
      );
  );
);

app.post("/stats", function(req, res)
    const favJournal = req.journal.id;
    User.findById(req.user.id, function(err, foundUser) 

        if (err) 
            console.log(err);
         else 
            if (foundUser) 
                foundUser.journal.push(favJournal);
                foundUser.save(function() 
                    res.redirect("/favourite");
                );
            
        
    );
);

【讨论】:

谢谢,但我已经拥有了所有这些,忘记包括在内。编辑问题以避免进一步混淆。

以上是关于使用提交按钮/输入标签将数据插入猫鼬模式的主要内容,如果未能解决你的问题,请参考以下文章

提交按钮的 HTML 不会将数据插入数据库并一起重定向到 URL

Javascript:单击提交按钮时如何将隐藏的输入标签附加到表单中?

表单学习心得

如何使用 Angular 收集多个表单提交并一次提交给猫鼬模型?

Django使用提交按钮发布文本而不使用输入标签

表单标签中的按钮不会提交或响应Javascript / Jquery