i m creating a small shop app with:
node.js & express and mongoose
and I m facing a problem when I try to send the data to the mongoose database
this is my product class
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const productSchema = new Schema({
title: { type: String, required: true },
price: { type: Number, required: true },
description: { type: String, required: true },
imageUrl: { type: String, required: true },
userId: { type: Schema.Types.ObjectId, required: true }
});
module.exports = mongoose.model("Product", productSchema);
and this is the function to send in the controller
exports.postAddProduct = (req, res, next) => {
console.log(req.user);
const product = new Product({
title: req.body.title,
price: req.body.price,
description: req.body.description,
imageUrl: req.body.imageUrl,
userId: req.user });
product
.save()
.then((result) => {
console.log("Product created!");
res.redirect("/admin/products");
})
.catch((err) => {
console.log(err);
});
};
and this is the error
Error: Product validation failed: userId: Path `userId` is required.
at ValidationError.inspect (C:UserslenovoDesktopCURRENT_PROJECTSnode_tutonode_modulesmongooseliberrorvalidation.js:48:26)
at formatValue (internal/util/inspect.js:745:19)
at inspect (internal/util/inspect.js:319:10)
also when I print the req.user
in the function exports.postAddProduct
it gives me undefined
this is app.JS
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.set("view engine", "ejs");
app.set("views", "./views");
const path = require("path");
const adminRoutes = require("./routes/admin");
const shopRoutes = require("./routes/shop");
const pageNotFoundController = require("./controllers/404");
const mongoose = require("mongoose");
const User = require("./models/user");
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, "public")));
app.use((req, res, next) => {
User.findById("62c71d0ab0312958a8082d6f")
.then((user) => {
console.log('user' + user)
req.user = user;
// next();
})
.catch((err) => console.log(err));
next();
});
app.use("/admin", adminRoutes.routes);
app.use(shopRoutes);
app.use(pageNotFoundController.getPageNotFound);
mongoose
.connect(
"HERE MY URL "
)
.then((result) => {
User.findOne().then((user) => {
if (!user) {
const user = new User({
name: 'Aimen',
email: 'Aimen@',
cart: {
items: []
}
});
user.save();
} else {
console.log('user already there');
}
});
console.log("Connected to MongoDB");
app.listen(3000);
})
.catch((err) => console.log(err));
2
Answers
the bug was because in the middleware i was commenting the next() fun so the programme was stopping there
Is your req.user a string on an object?
If is a string you can try something like: mongoose.Types.ObjectId(string).