NodeJS + MongoDB _message: 'book validation failed' - javascript

I just start learning NodeJS and MongoDB. Now ı am working on a small project to learn basic stuff. But ı am getting a error, in this project ı try to insert data to mongodb which is,
userid like;
"5ed6bfe86034a81dbc7226aa" created from random numbers and letters.
But ı can not insert id to mongodb ı got an error. Here is my codes.
Firstly here is my model which is "Book.js"
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const BookSchema = new Schema({
title: {
type: String,
required: true,
},
userid: Schema.Types.ObjectId, //ı defined here no problem.
published: {
type: Boolean,
default: false
},
So, in routes folder my "book.js" like this;
var express = require('express');
var router = express.Router();
//Models
const Book = require('../models/Book');
const User = require('../models/Users');
/* GET book page. */
router.post('/new', function(req, res, next) {
const book = new Book({
title: 'Node JS',
userid: BigInt, //ı got error here.
//what ı should write?
meta: {
votes: 12,
favs: 90
},
category: "History"
});
book.save((err, data) => {
if (err)
console.log(err);
res.json(data);
});
});
so when ı run my server and try to post data to mongodb with using postman ı got an error.
Like this; _message: 'book validation failed',
and more information: Error: book validation failed: userid: Cast to ObjectId failed for value "[Function: BigInt]" at path "userid"
Now, how can ı define "userid" variable? why ı got an error? what ı should write to define userid for mongodb to post data successfully? Thanks in advance.

I think you need to store the _id created in user schema
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const BookSchema = new Schema({
title: {
type: String,
required: true,
},
userid: {
type:Schema.Types.ObjectId,
ref:User,
required:true
},
published: {
type: Boolean,
default: false
},
Then you need to fetch the user id and then store it to Book collection. By specifying ref keyword you can use populate method provided by mongoose to fetch the user info using book schema.
Example program to fetch and save _id
exports.postaddFoods=(req,res,next)=>{
const foodname=req.body.foodname;
const image=req.body.image;
const shopname=req.shop.shopName;
const price=req.body.price;
Shop.findOne({shopName:shopname})
.then(sid=>{
const food= new Food({
foodName:foodname,
image:image,
shopName:shopname,
price:price,
shopId:sid._id
});
return food.save()
})

This is not a solution
#Dharani Shankar , here is my routes/book.js
router.post('/new', (req,res,next) => {
Book.findOne({title: "NodeJS"})
.then(sid => {
const book = new Book({
title: "Node JS",
meta: {
votes: 12,
favs: 90
},
category: "History",
userid: sid._id
});
book.save((err, data) => {
if (err)
console.log(err);
res.json(data);
});
});
});
sorry for late reply. Note: I have to post my data from that url "localhost:3000/books/new" ı am using postman for testing.

Related

Express/mongoose returns empty array when trying to get request

I am trying to get the list of books from the database. I inserted the data on mongoose compass. I only get an empty array back.
//Model File
import mongoose from "mongoose";
const bookSchema = mongoose.Schema({
title: {
type: String,
required: true,
},
description: {
type: String,
required: true,
},
releasedDate: {
type: String,
required: true,
},
});
const Book = mongoose.model("Book", bookSchema);
export default Book;
//Routes file
import express from "express";
import Book from "./bookModel.js";
const router = express.Router();
router.get("/", async (req, res) => {
const books = await Book.find({});
res.status(200).json(books);
});
make sure you have books data in db.if it is there then try to add then and catch blocks to your code. Then you will get to know what is the error.
await Book.find({})
.then((data) =>{
res.send(data)
})
.catch((err) =>{
res.send(err)
})
When you create your model, change mongoose.model by new Schema and declare _id attribute like:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
const Book = new Schema({
_id: { type: Schema.ObjectId, auto: true },
// other attributes
})
Update: If it doesn't seem to work, try changing _id with other names such as bookID or id, that can be the error, read https://github.com/Automattic/mongoose/issues/1285

Menu API data not showing

I am trying to make API for sample Menu Data in which the data must be fetched and shown by entering Restaurant ID. Controller, Model and Router is set but I load it in Postman the data is not showing also if I console.log() the result, its showing an empty array. Please share your ideas. Thanks in advance.
Controller (Menu.js)
const Menu = require('../Models/Menu');
exports.getMenu = (req, res) => {
Menu.find({
restID: req.params.restID
}).then(result => {
res.status(200).json({
menus: result,
message: "Menu Data Success"
});
console.log(result);
}).catch(error => {
res.status(500).json({
message: error
});
})
}
Model (Menu.js)
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const MenuSchema = new Schema({
item: {
type: String,
required: true
},
cost: {
type: Number,
required: true
},
description: {
type: String
},
restID: {
type: Number,
required: true
}
});
module.exports = mongoose.model('menus', MenuSchema, 'Menu');
Router (router.js)
const express = require('express');
const MenuController = require('../Controllers/Menu');
const router = express.Router();
router.get('/restaurantMenu/:restID',MenuController.getMenu);
module.exports = router;

is this code true to query all documents in mongodb via mongoose?

i'm using MongooseJS and doesn't return anything in console or res.json
is it about find function ?
const router = require("express").Router();
var Panel = require("../models/Panel");
router.get("/panels", (req, res) => {
Panel.find({}, function(err, panels) {
if (err) res.send(err);
console.log(panels);
res.json(panels);
});
});
This is the mongoose model for Panel section
const mongoose = require("mongoose");
const Panel = mongoose.model(
"Panel",
new mongoose.Schema({
name: String,
const: Number,
salons: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Salon"
}
]
})
);
module.exports = Panel;
Problem solved, by catching errors, and trying to use anyone can access database, it was about my proxy :)

Im doing POST method to my API using EXPRESS ROUTER and this does not work

I'm working on API project for client.
The problem is using POSTMAN when i hit POST method the status I get is Status: 500 TypeError.
I tried put some data to my DATABASE manually so that I can check if my CRUD method is working. The GET method is working fine.
This is the API route i created:
const express = require('express')
const Client = require('../../models/Client')
const router = express.Router()
// Get Client
router.get('/', (req, res) => {
Client.find()
.sort({date: -1})
.then(clients => res.json(clients))
.catch(err => res.status(404).json(err))
})
// Create Client
router
.post('/', (req, res) => {
const newClient = new Client({
name: req.body.name,
email: req.body.email,
phone: req.body.phone,
})
newClient
.save()
.then(client => res.json(client))
.catch(err => console.log(err))
})
module.exports = router
This is my Model:
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const ClientSchema = new Schema({
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
},
phone: {
type: String,
required: true,
},
created_at: {
type: Date,
default: Date.now
},
updated_at: {
type: Date,
default: Date.now
},
})
module.exports = Client = mongoose.model("client", ClientSchema);
ERROR Message: Cannot read property 'name' of undefined.
I tried all I can do, changing some code, hard coded some fields, but nothing works.
How to fix the error I get?

Mongoose ODM on Index could not get any response in client application

Currently i am working on Express with Mongoose ODM to build a RESTful API for my mobile app. In my Mongoose Schema i have a title: Index field. I follow Mongoose Unique Index Validation Document to create Unique Document in MongoDB, bellow is my code
Mongoose Schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var CategorySchema = new Schema({
title: { type: String, required: true, index: true, unique: true },
details: { type: String, required: false },
thumbnail: { type: String, required: false },
created: { type: Date, default: Date.now },
modified: { type: Date, default: Date.now }
});
module.exports = mongoose.model('Category', CategorySchema);
Express Code
var express = require('express');
var routes = express.Router();
var Category = require('./models/category.model');
routes.route('/categories')
.post(function(req, res) {
Category.on('index', function(error) {
if(error) {
res.send(error);
}
Category.create({ title: req.body.title, details: req.body.details,
thumbnail: req.body.thumbnail }, function(error) {
if(error) {
res.send(error);
}
res.json({ message: 'Category was save successfully..!' });
});
});
});
Problem:
Now my problem is that, when i send a POST request to my API http://localhost:3000/api/v1.0/categories. It will not send any response to my client application. This will not show any Warning or Error in server console.
I don't see the point in having
Category.on('index', function(error) {
if(error) {
res.send(error);
}
}
there. Do you want to listen to the index event inside a controller function? Probably not.
You can move
Category.create({ title: req.body.title, details: req.body.details,
thumbnail: req.body.thumbnail }, function(error) {
if(error) {
res.send(error);
}
res.json({ message: 'Category was save successfully..!' });
});
out of it. You should also make sure you return after sending a response, otherwise you might end up sending several responses. Inside if(error) you do a res.send(error) but it will continue to the res.json() later.
So if the rest of your code is correct then this might work:
var express = require('express');
var routes = express.Router();
var Category = require('./models/category.model');
routes.route('/categories').post(function(req, res) {
Category.create({
title: req.body.title,
details: req.body.details,
thumbnail: req.body.thumbnail
}, function(error) {
if(error) {
return res.status(500).json(error);
}
return res.status(201).json({ message: 'Category was save successfully..!' });
});
});
You will get an error message if you break the unique constraint for title. This will happen when you do the create. You have to restart the app before the unique constraint starts working.

Categories

Resources