我是编码和Node.js的新手,我相信这个问题可能仅仅是我缺乏Node.js /编码的经验。 该代码在下面发布,有关更多信息,我已经发布了Github文件
我试图将对象ID从一个函数调用到另一个函数,以便可以关联父函数和子函数。
具体来说(在文件 users.js 中),我试图从函数 router.post(“ / register”,( req,res)到功能 router.post(“ / registerCar”,(req,res)),但是每当我尝试在菜单中调用 newUser 变量时, registerCar 函数似乎为空。即使我调用 User._id ,该函数也似乎为空。
我正在尝试弄清楚如何将 newUser 的对象ID调用到 newCar 。
我尝试过的事情:
我试图将 router.post(“ / registerCar”,(req,res)添加到 router.post(“ / register”,(req, res),但每当我尝试提交汽车登记表时,都会显示“找不到方法POST registerCar”或
将 newUser 设置为全局变量,但是由于某些原因,我无法在 router.post(“ / registerCar”,(req,res)中调用它
在 router.post(“ / register”,(req,res))函数中尝试了回调参数,但这并没有真正起作用(尽管我可能做错了)< / p>
我尝试将 _id:Schema.Types.ObjectId; 添加到User.js和Car.js中,但它给我一个错误“错误[MongooseError]:文档必须具有_id在保存到新的MongooseError之前”。我试图为此研究一种解决方案,但没有任何进展。
我知道很多事情,但是我正在努力提高自己的编码技能,而我被困在这里已经两天了。如果你们能帮助我,我将不胜感激。
___________________________________________________________________________________________________
// User.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
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,
},
carType: [{
type: Schema.Types.ObjectId,
ref: 'Car'
}]
});
const User = mongoose.model('User', UserSchema);
module.exports = User;
___________________________________________________________________________________________________
//Car.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const UserModel = new mongoose.Schema({
carMake: {
type: String,
require: true,
},
carModel: {
type: String,
require: true,
},
carid: [{
type: Schema.Types.ObjectId,
ref: 'User'
}]
});
const Car = mongoose.model('Car', UserModel);
module.exports = Car;
___________________________________________________________________________________________________
//users.js
const express = require("express");
const router = express.Router();
const bcrypt = require("bcryptjs");
const passport = require("passport");
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
// User model
const User = require("../models/User");
//Cars model
const Car = require("../models/Car");
//Login
router.get("/login", (req, res) => res.render("login"));
//Register Page
router.get("/register", (req, res) => res.render("register"));
//test page
router.get("/test", (req, res) => res.render("test"));
//registerCar Page
router.get("/registerCar", (req, res) => res.render("registerCar"));
// Register Handle
router.post("/register", (req, res) => {
const { name, email, password, password2 } = req.body;
let errors = [];
// Check required fields
if (!name || !email || !password || !password2) {
errors.push({ msg: "Please fill in all fields." });
}
// Check passwords match
if (password != password2) {
errors.push({ msg: "Passwords do not match." });
}
// Check pw length
if (password.length < 6) {
errors.push({ msg: "Password should be longer than 6 characters." });
}
// Issue present
if (errors.length > 0) {
res.render("register", {
errors,
name,
email,
password,
password2,
});
} else {
// Validation passed
User.findOne({ email: email }).then((user, callback) => {
if (user) {
// User exists
errors.push({ msg: "Email is already registered" });
res.render("register", {
errors,
name,
email,
password,
password2,
});
} else {
const newUser = new User({
name,
email,
password,
});
// Hash Password
bcrypt.genSalt(10, (err, salt) =>
bcrypt.hash(newUser.password, salt, (err, hash) => {
if (err) throw err;
//Set password to hashed
newUser.password = hash;
//Save user
newUser
.save()
.then((user) => {
req.flash(
"success_msg",
"You are now registered. Please log in."
);
res.redirect("/users/login");
})
.catch((err) => console.log(err));
})
);
}
});
}
});
// Login Handle
router.post("/login", (req, res, next) => {
passport.authenticate("local", {
successRedirect: "/dashboard",
failureRedirect: "/users/login",
failureFlash: true,
})(req, res, next);
});
//Logout Handle
router.get("/logout", (req, res) => {
req.logout();
req.flash("success_msg", "You are logged out");
res.redirect("/users/login");
});
// Car registration Handle
router.post("/registerCar", (req, res) => {
const { carMake, carModel, carid } = req.body;
let errors = [];
const newCar = new Car({
carMake,
carModel,
carid, //want to call User ID over here
});
newCar
.save()
.then((car) => {
console.log(newCar._id);
res.redirect("/dashboard");
})
.catch((err) => console.log(err));
});
module.exports = router;
___________________________________________________________________________________________________