skip to Main Content

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


  1. Chosen as BEST ANSWER

    the bug was because in the middleware i was commenting the next() fun so the programme was stopping there


  2. Is your req.user a string on an object?
    If is a string you can try something like: mongoose.Types.ObjectId(string).

    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: mongoose.Types.ObjectId(req.user)
      });
      product
        .save()
        .then((result) => {
          console.log("Product created!");
          res.redirect("/admin/products");
        })
        .catch((err) => {
          console.log(err);
        });
    };
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search