Error: Product validation failed: path: Path `path` is required - javascript

I keep getting this error message whenever i try to populate my "product" page from MongoDB.
I have added the body-parser dependency.
N.B
I stored the product images in my Public folder and i am storing the imagePath in MongoDB.
Here's a snippet of my code
From my App.js
const express = require('express');
const ejs = require('ejs');
const mongoose = require('mongoose');
const bodyparser = require('body-parser');
const Product = require('./models/products');
From my product Model...
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const productSchema = new Schema({
path: {
type: String,
required: true
},
title: {
type: String,
required: true
},
price: {
type: Number,
required: true
},
},
{timestamps : true});
const Product = mongoose.model('Product', productSchema);
module.exports = Product;
Also from my App.js files
app.get('/product/create', (req, res) => {
res.render('upload', { title: 'Add Products'});
});
app.post('/', (req, res) => {
console.log(req.body);
})
//Looping through all products
app.get('/product', (req, res) => {
Product.find().sort({ createdAt: -1})
.then((result) => {
res.render('product', { title: 'All Products', products : result})
})
.catch((err) => {
console.log(err);
})
});
//POST request to product route
app.post('/product', (req, res) => {
const product = new Product(req.body);
product.save()
.then((result) => {
res.redirect('/product');
})
.catch(err => console.log(err));
});

Related

error Product validation failed: userId: Path `userId` is required in nodejs a

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:\Users\lenovo\Desktop\CURRENT_PROJECTS\node_tuto\node_modules\mongoose\lib\error\validation.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));
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);
});
};
the bug was because in the middleware i was commenting the next() fun so the programme was stopping there

Unable to access object properties while doing a post request

I am creating a post request that adds new posts to MongoDB. The post request works well and I can see the post in Mongo.
I am struggling at accessing properties from the object using req.body, specifically req.body._id. I would like to console.log the req.body._id to verify that it worked. In the terminal, I keep on getting 'undefined'.
All the solutions I have seen so far say include app.use(express.json()); and app.use(express.urlencoded({ extended: false })); which I have.
I am stumped on what to try next. Any suggestions would be appreciated.
Here is my server.js file
const express = require('express');
const dotenv = require("dotenv").config();
const mongoose = require('./db/mongoose');
const app = express();
const postsRoute = require('./routes/posts');
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use("/posts", postsRoute);
app.listen( process.env.PORT || 5000, (err) => {
console.log(`listening on port ${process.env.PORT}`);
});
Here is my routes file
const express = require('express');
const router = express.Router();
const { allPosts, createPost } = require('../db/models/postModel');
router.get("/", async (req, res) => {
console.log(`req.title is: ${req.title}`);
try {
const posts = await allPosts();
res.send(posts);
} catch (err) {
console.log(err.message);
}
});
router.post("/create", async (req, res) => {
const newPost = req.body;
try {
const addingPost = await createPost(newPost);
console.log(`req.body is:${addingPost}`);
console.log(`req.body title:${addingPost.title}`);
console.log(`addingPost is: ${addingPost} with id of ${addingPost._id}`);
res.send (addingPost);
} catch (err) {
res.status(500).send(err.message);
}
});
module.exports = router;
Here is my Schema file
const mongoose = require('mongoose');
const { Schema } = mongoose;
const postSchema = new Schema({
author: {
type: String,
required: true
},
title: {
type: String,
required: true
},
content: {
type: String,
required: true,
},
tags: [String],
file: String,
likes: {
type: Number,
//We want to default to 0 likes
default: 0,
},
createdAt: {
type: Date,
default: new Date(),
},
});
const postModel = mongoose.model('Post', postSchema);
//Get all posts
const allPosts = async () => {
const posts = await postModel.find();
return posts;
};
//Create posts
const createPost = async (post) => {
const newPost = await postModel.create(post);
return newPost;
};
module.exports = { allPosts, createPost };
Console.log outputs in the Node REPL
I have included a picture showing what the console.log ouputs in the terminal. Hopefully this supports my question.

how to save data into mongodb using express?

Trying to create signin and signup using express and MongoDB. In postman the data is perfectly passed but couldn't save the data into mongoDB cluster.
IN this file connection to the db is created and also confused whether i am connected to the db or not in this file, I created schema for the user details to be provided
//Index.js
const express = require("express");
const mongoose = require("mongoose");
const app = express();
const dotenv = require("dotenv");
dotenv.config();
const db = process.env.DATABASE;
mongoose.connect(db, { useNewUrlParse: true }, () =>
console.log("connected to db")
);
//midlewares
app.use(express.json());
//importing routes
const authRoute = require("./routes/auth");
//route middle wares
app.use("/api/user", authRoute);
app.listen(3000, () => console.log("gg server is running"));
//User.js
const mongoose = require("mongoose");
const { Schema } = mongoose;
const userSchema = new Schema({
name: {
type: String,
max: 32,
required: true,
min: 6,
},
email: {
type: String,
required: true,
max: 32,
},
password: {
type: String,
max: 1022,
min: 8,
required: true,
},
date: {
type: Date,
default: Date.now,
},
});
module.exports = mongoose.model("User", userSchema);
//Auth.js
const router = require("express").Router();
const User = require("../model/User");
router.post("/register", (req, res) => {
const user = new User({
name: req.body.name,
email: req.body.email,
password: req.body.password,
});
const name = {
name: req.body.name,
email: req.body.email,
};
res.send(user);
user.save();
});
module.exports = route[![enter image description here][1]][1]r;
Step 1
First, you should create a server after your MongoDB is connected. So, put your server logic inside mongoose.connect connect. This will assure that when yo u try to create a new user, MongoDB is already connected.
mongoose.connect(db, { useNewUrlParse: true }, () =>
console.log("connected to db");
//midlewares
app.use(express.json());
//importing routes
const authRoute = require("./routes/auth");
//route middle wares
app.use("/api/user", authRoute);
app.listen(3000, () => console.log("gg server is running"));
);
Step 2
Use create method to create new user document:
router.post("/register", async (req, res) => {
const user = await User.create({
name: req.body.name,
email: req.body.email,
password: req.body.password,
});
return res.status(200).json(user);
});

Save data to MongoDB using NodeJS

I am trying to pass data to a MongoDB collection and it returns Cannot POST /courseweb/course/add
Before passing values through axios I tried postman (a google extension) to send data.
This is my server.js which is implemented with expressjs
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const Bundler = require("parcel-bundler");
const cors = require("cors");
const mongoose = require("mongoose");
const InstructorDB = require('./public/DBModels/InstructorDB');
const router = express.Router();
const bundler = new Bundler("./src/index.html");
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(bundler.middleware());
// app.use(express.static('./src'));
app.use("/courseweb", router);
mongoose.connect("mongodb://127.0.0.1:27017/courseweb", {
useNewUrlParser: true
});
const connection = mongoose.connection;
connection.once("open", () => {
console.log("Connected to MongoDB via 27017");
});
app.listen(3000, err => {
if (err) {
console.error(err);
process.exit(-1);
}
console.log("Application is running on port 3000");
});
app.get("/", function(req, res) {
res.sendFile("./dist/index.html");
});
router.route('/course/add').post((req, res) => {
let instructorDB = new InstructorDB(req.body);
instructorDB.save().then(bookDB => {
res.status(200).send(`${bookDB} Added`);
}).catch((err) => {
res.status(400).send({message: err});
});
});
router.route('/courses').get((req, res) => {
// name of the course database model here
InstructorDB.find().count(function(err, count){
res.status(200).send(count);
});
});
And this is my InstructorDB.js which is a schema model by mongoose
const mongoose= require('mongoose');
const Schema = mongoose.Schema;
let InstructorDB = new Schema({
firstName: String,
lastName: String,
designation: String,
faculty: String,
contactNumber: Number,
email: String,
password: String,
isEnabaled: Boolean,
courses: [{courseID: String}]
});
module.exports = mongoose.model('InstructorDB', InstructorDB, 'InstructorDB');
And this is a screenshot and the response I get when I pass the values through postman. I have set header as content-type and application/json too
Can anyone tell me where I have gone wrong?
Make sure you send the right data via your post request and change the verb to post :
app.post('/course/add', (req, res) => {
if(req.body == null){
return res.status(400).send({message: 'bad request'});
}
let instructorDB = new InstructorDB(req.body);
instructorDB.save((err ,doc ) => {
if(err){
res.status(400).send({message: err});
}
res.status(200).send(`Added`);
});
});
You don't need router if you're going to put it in the same file.
try this syntax instead:
app.post('/coureweb/course/add',((req, res) => {
let instructorDB = new InstructorDB(req.body);
instructorDB.save().then(bookDB => {
res.status(200).send(`${bookDB} Added`);
}).catch((err) => {
res.status(400).send({message: err});
});
}));
then take out
app.use("/courseweb")

Mongoose: TypeError: 'mongooseSchemahere' is not a function

I have the following mongoose Schema setup in models/user.js:
const mongoose = require('mongoose');
const userSchema = mongoose.Schema({
loginId: String,
firstname: String,
lastname: String,
eMail: String,
password: String,
active: Boolean
});
module.exports = userSchema;
In my main app.js I have the following code:
const mongoose = require('mongoose');
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, {
useUnifiedTopology: true,
useNewUrlParser: true,
},function(err, db) {
if (err) throw err;
var dbo = db.db("db");
dbo.collection("db").find({}).toArray(function(err, result) {
if (err) throw err;
console.log(result);
db.close();
});
});
let userSchema = require('./models/user.js');
// Get single user
app.get('/user/:id', function (req, res) {
userSchema.findById(req.params.id, (error, data) => {
if (error) {
return next(error)
} else {
res.json(data)
}
})
})
I get the error which is in the title (just replace mongooseSchemahere with userSchema). What did I do wrong? I tried putting the userSchema declaration in different places, it did not help..
You need to use mongoose.connect to work with mongoose models.
Make these changes:
1-) Create the user model like this and export:
const mongoose = require("mongoose");
const userSchema = new mongoose.Schema({
loginId: String,
firstname: String,
lastname: String,
eMail: String,
password: String,
active: Boolean
});
module.exports = mongoose.model("User", userSchema);
2-) Change your App.js to connect your db with mongoose.connect:
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const User = require("./models/user");
const url = "mongodb://localhost:27017/mydb";
const port = process.env.PORT || 3000;
app.use(express.json());
mongoose
.connect(url, {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => {
app.listen(port, () => {
console.log(`App running on port ${port}...`);
});
})
.catch(error => console.log(error));
Now you can create a user like this:
app.post("/user", function(req, res, next) {
console.log("Req body:", req.body);
User.create(req.body)
.then(result => {
console.log({ result });
res.send(result);
})
.catch(err => {
console.log(err);
res.status(500).send("something went wrong");
});
});
To retrieve the user by _id:
app.get("/user/:id", function(req, res, next) {
User.findById(req.params.id, (error, data) => {
if (error) {
return next(error);
} else {
res.json(data);
}
});
});
To retrieve a user by firstname: (if you want to find all users by firstname change findOne to find.):
app.get("/user/firstname/:firstname", function(req, res, next) {
console.log(req.params.firstname);
User.findOne({ firstname: req.params.firstname }, (error, data) => {
if (error) {
return next(error);
} else {
res.json(data);
}
});
});
You need to export the model and not the schema.
const mongoose = require('mongoose');
const userSchema = mongoose.Schema({
loginId: String,
firstname: String,
lastname: String,
eMail: String,
password: String,
active: Boolean
});
module.exports = mongoose.model('user', userSchema);
Now you can do things like:
let User = require('./models/user.js');
// Get single user
app.get('/user/:id', function (req, res) {
User.findById(req.params.id, (error, data) => {
if (error) {
return next(error)
} else {
res.json(data)
}
})
})

Categories