Given a Schema like this:
new Schema(
{
someData: {
someString: {
required: false,
maxlength: 400,
type: String
}
otherData: {
required: true,
type: String
}
});
someString is optional but has a validation to check if it's length is below 400.
If I'm given an invalid length string (>400) would this object still be saved but without the someString or would this throw an error? If this throws an error how can I change the schema so that the object will still get saved?
It will throw an error without saving the document.
Let's say we have this schema:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const studentSchema = new Schema({
someData: {
someString: {
required: false,
maxlength: 5,
type: String
},
otherData: {
required: true,
type: String
}
}
});
module.exports = mongoose.model("Student", studentSchema);
And this post route:
const Student = require("../models/student");
router.post("/students", async (req, res) => {
try {
const result = await Student.create(req.body);
res.send(result);
} catch (err) {
console.log(err);
if (err.name === "ValidationError") {
return res.status(400).send(err.errors);
}
res.status(500).send("Something went wrong");
}
});
When we send a bad request it will give ValidationError where we can read the error details from err.errors.
Request Body:
{
"someData": {
"someString": "123456",
"otherData": "other"
}
}
The response will be:
{
"someData.someString": {
"message": "Path `someData.someString` (`123456`) is longer than the maximum allowed length (5).",
"name": "ValidatorError",
"properties": {
"message": "Path `someData.someString` (`123456`) is longer than the maximum allowed length (5).",
"type": "maxlength",
"maxlength": 5,
"path": "someData.someString",
"value": "123456"
},
"kind": "maxlength",
"path": "someData.someString",
"value": "123456"
}
}
You can resolve this by removing the maxlength option, or check the field's length in your route, and if it's length is bigger than the specified maxlength, you can substr it so that it doesn't result in error.
router.post("/students", async (req, res) => {
try {
let doc = req.body;
if (doc.someData && doc.someData.someString && doc.someData.someString.length > 5) {
doc.someData.someString = doc.someData.someString.substring(0, 5);
}
const result = await Student.create(doc);
res.send(result);
} catch (err) {
console.log(err);
if (err.name === "ValidationError") {
return res.status(400).send(err.errors);
}
res.status(500).send("Something went wrong");
}
});
Related
From the Fastify documentation in the section titled Using other validation libraries I'm trying to get yup to validate my schema but I keep getting schema.validateSync is not a function and I don't know why??
I want the schema to still be valid for creating the swagger document but I want to use yup to give me the validation I need.
const yup = require("yup");
const yupOptions = {
strict: false,
abortEarly: false,
stripUnknown: true,
recursive: true,
};
async function isUsernameAvailable(fastify: any, _options: Object) {
const users = fastify.mongo.db.collection("users");
fastify.get(
"/api/v1/onboarding/isUsernameAvailable/:username",
{
schema: {
params: {
type: "object",
properties: {
username: { type: "string", maxLength: 12, minLength: 1 },
},
required: ["username"],
},
response: {
200: {
type: "object",
properties: {
available: {
type: "boolean",
description: "Returns true if username is available",
},
},
},
},
},
validatorCompiler: ({ schema, method, url, httpPart }: any) => {
return function (data: any) {
try {
const result = schema.validateSync(data, yupOptions);
return { value: result };
} catch (e) {
return { error: e };
}
};
},
},
async (request: any, _reply: any) => {
const { username } = request.params;
const foundNUsernames = await users.countDocuments(
{ username },
{ limit: 1 }
);
const available: boolean = foundNUsernames === 0;
return { available };
}
);
}
export { isUsernameAvailable };
if I use the below, the validation works but the swagger doc doesn't build
schema: {
params: yup.object({
username: yup.string().lowercase().max(12).min(1).required(),
}),
}
if I remove the validatorCompiler then I get no errors, swagger does build but I cant use yup
validatorCompiler: ({ schema, method, url, httpPart }: any) => {
return function (data: any) {
try {
const result = schema.validateSync(data, yupOptions);
return { value: result };
} catch (e) {
return { error: e };
}
};
},
}
how can I satisfy both?
Why do I want to use yup? I want to validate emails and transform values into lowercase.
Can anyone please tell me where to place the $jsonSchema in the following code. Every time I test post my code returns the status(400) success: false.
All I'm trying to do is validator the title and description have been entered correctly.
import { connectToDatabase } from "../../../util/mongodb";
export default async (req, res) => {
const { method } = req;
const { db } = await connectToDatabase();
switch (method) {
case "GET":
try {
const products = await db.collection("products").find({}).toArray();
res.status(200).json({ success: true, data: products });
} catch (error) {
res.status(400).json({ sucess: false });
}
break;
case "POST":
try {
const product = await db
.collection("products")
.insertOne(req.body)
.runCommand({
collMod: "products",
validator: {
$jsonSchema: {
bsonType: "object",
required: ["title", "description"],
properties: {
title: {
bsonType: "string",
description: "must be a string and is required",
unique: true,
},
description: {
bsonType: "string",
description: "must be a string and is required",
},
},
},
},
});
res.status(201).json({ success: true, data: product });
} catch (error) {
res.status(400).json({ sucess: false });
}
break;
default:
res.status(400).json({ dsucess: false });
break;
}
};
I have the following resolver for GraphQL:
const Post = require("../../models/Post");
module.exports = {
getAllActivePosts: async (userId) => {
try {
const posts = await Post.find({
userId: userId
})
.select(["name", "createdAt"])
.populate("posts", ["name", "createdAt"]);
return posts;
} catch (err) {
console.log(err);
throw err;
}
},
};
which tries to get all active posts by the ID of the user from the Post model:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const PostSchema = new mongoose.Schema({
userId: {
type: Schema.Types.ObjectId,
ref: "User",
required: true,
},
content: {
type: String,
required: true,
},
createdAt: {
type: Date,
required: true,
}
});
module.exports = Post = mongoose.model("Post", PostSchema);
Here's the GraphQL Schema:
const { buildSchema } = require('graphql');
module.exports = buildSchema(`
type User {
_id: MongoId!
email: String!
password: String
}
type Post {
_id: MongoId!
userId: MongoId!
content: String!
createdAt: String!
}
scalar MongoId
input LoginInput {
email: String!
password: String!
}
type RootQuery {
login(email: String!, password: String!): AuthData!
getAllActivePosts(userId: MongoId!): [Post]
}
type RootMutation {
createUser(loginInput: LoginInput): AuthData!
}
schema {
query: RootQuery
mutation: RootMutation
}
`);
... and the GraphQL query I'm running in GraphiQL:
{
getAllActivePosts(userId: "5fbfc92312b90071179a160f") {
name
createdAt
}
}
For this, the result of the query is:
{
"errors": [
{
"message": "Cast to ObjectId failed for value \"{ userId: '5fbfc92312b90071179a160f' }\" at path \"userId\" for model \"Post\"",
"locations": [
{
"line": 2,
"column": 3
}
],
"path": [
"getAllActivePosts"
]
}
],
"data": {
"getAllActivePosts": null
}
}
Searched here for similar issues, tried wrapping userId in ObjectId, but nothing helped. What am I missing here?
I was go through this problem once a year ago with no solution till i get main concept of graphql.
Here you are passing string
{
getAllActivePosts(userId: "5fbfc92312b90071179a160f") {
name
createdAt
}
}
and graphql expecting to have mongoose.Types.ObjectId
getAllActivePosts(userId: MongoId!): [Post]
You need to do sync like
getAllActivePosts(userId: mongoose.Types.ObjectId("5fbfc92312b90071179a160f")) {
But using above way you are not eligible for run query in graphiQL becuse there is no mongoose defined.
type RootQuery {
login(email: String!, password: String!): AuthData!
getAllActivePosts(userId: String!): [Post]
}
Better solution is use userId input as string and then validate on your resolver function like
getAllActivePosts: async ({ userId }) => {
try {
if(mongoose.Types.ObjectId.isValid(userId)) {
const posts = await Post.find({
userId: userId
})
.select(["name", "createdAt"])
.populate("posts", ["name", "createdAt"]);
// you can;t return null you need to return array
return posts ? posts : []
} else {
// if mongoose id is wrong
return []
}
} catch(error) {
// it is better to throw error return blank array to complete flow
throw error
}
}
Turned out, I was using userId directly, whereas I should've used args.userId. The proper resolver below:
module.exports = {
getAllActivePosts: async (args) => {
try {
const posts = await Post.find({
userId: args.userId
})
.select(["name", "createdAt"])
.populate("posts", ["name", "createdAt"]);
return posts;
} catch (err) {
console.log(err);
throw err;
}
},
};
and for the schema:
getAllActivePosts(userId: String!): [Post]
i am testing my mongoose (for MongoDB) schema, and I encountered an validation issue. After making POST verb I am getting en error:
"message": {
"errors": {
"number": {
"message": "Path `number` is required.",
"name": "ValidatorError",
"properties": {
"message": "Path `number` is required.",
"type": "required",
"path": "number"
},
"kind": "required",
"path": "number"
}
},
"_message": "eventArrayModel validation failed",
"message": "eventArrayModel validation failed: number: Path `number` is required.",
"name": "ValidationError"
}
This is my mocked json in Postman:
JSON mocked file
{
"arrayName": "displayedEvents",
"number": "4"
}
And this is my mongoose schema:
const mongoose = require("mongoose");
const eventSchema = new mongoose.Schema({
title: {
type: String,
// required: true,
},
start: {
type: Date,
// required: true,
},
end: {
type: Date,
// required: true,
},
allDay: {type: Boolean, default: true},
resource: {
type: String,
// required: true,
},
});
const eventArrayModel = mongoose.model("eventArrayModel", {
arrayName: {
type: String,
required: true,
},
array: {type: [eventSchema]} ,
number: {
type: Number,
required: true,
}
});
module.exports = eventArrayModel;
And the get router:
router.get('/', async (req,res)=> {
try{
const posts = await eventArrayModel.find();
res.json(posts);
}catch(err){
res.json({message: err});
}
});
I can't see anything wrong about this code. It works fine without number field.
Okey I found it, this part of code
router.post('/', async(req,res)=>{
const post = new eventArrayModel({
arrayName: req.body.arrayName
});
try {
const savedPost = await post.save();
res.json(savedPost);
}catch(err){
res.json({message: err});
}
});
Should looks more like this:
router.post('/', async(req,res)=>{
const post = new eventArrayModel({
arrayName: req.body.arrayName,
array: req.body.array,
myNumber: req.body.myNumber
});
try {
const savedPost = await post.save();
res.json(savedPost);
}catch(err){
res.json({message: err});
}
});
I use update Query for push some data in array in Mongodb and I use mongoose in nodeJs.Pplease anyone can help out from this.
Model Schema :
var mongoose = require('mongoose')
var Schema = mongoose.Schema;
var bcrypt = require('bcrypt')
var schema = new Schema({
email: { type: String, require: true },
username: { type: String, require: true },
password: { type: String, require: true },
creation_dt: { type: String, require: true },
tasks : []
});
module.exports = mongoose.model('User',schema)
So I use this schema and I want to push data in tasks array and here is my route code for pushing data.
Route For Update Data in Tasks:
router.post("/newTask", isValidUser, (req, res) => {
addToDataBase(req, res);
});
async function addToDataBase(req, res) {
var dataa = {
pName: req.body.pName,
pTitle: req.body.pTitle,
pStartTime: req.body.pStartTime,
pEndTime: req.body.pEndTime,
pSessionTime: req.body.pSessionTime,
};
var usr = new User(req.user);
usr.update({ email: req.user.email }, { $push: { tasks: dataa } });
console.log(req.user.email);
try {
doc = await usr.save();
return res.status(201).json(doc);
} catch (err) {
return res.status(501).json(err);
}
}
Here I create a async function and call that function in route but when I post data using postman it response with status code 200(success) but it updates nothing in my database.
Output screenshot:
as you can see in this image task : [].. it updates nothing in that array but status is success
I don't know why is this happening.
You can achieve this task easier using findOneAndUpdate method.
router.put("/users", isValidUser, async (req, res) => {
var data = {
pName: req.body.pName,
pTitle: req.body.pTitle,
pStartTime: req.body.pStartTime,
pEndTime: req.body.pEndTime,
pSessionTime: req.body.pSessionTime,
};
try {
const user = await User.findOneAndUpdate(
{ email: req.user.email },
{
$push: {
tasks: data,
},
},
{ new: true }
);
if (!user) {
return res.status(404).send("User with email not found");
}
res.send(user);
} catch (err) {
console.log(err);
res.status(500).send("Something went wrong");
}
});
Also I strongly suggest using raw / JSON data for request body, that's how most ui libraries (reactjs, angular) send data.
To be able to parse json data, you need to add the following line to your main file before using routes.
app.use(express.json());
TEST
Existing user:
{
"tasks": [],
"_id": "5e8b349dc285884b64b6b167",
"email": "test#gmail.com",
"username": "Kirtan",
"password": "123213",
"creation_dt": "2020-04-06T14:21:40",
"__v": 0
}
Request body:
{
"pName": "pName 1",
"pTitle": "pTitle 1",
"pStartTime": "pStartTime 1",
"pEndTime": "pEndTime 1",
"pSessionTime": "pSessionTime 1"
}
Response:
{
"tasks": [
{
"pName": "pName 1",
"pTitle": "pTitle 1",
"pStartTime": "pStartTime 1",
"pEndTime": "pEndTime 1",
"pSessionTime": "pSessionTime 1"
}
],
"_id": "5e8b349dc285884b64b6b167",
"email": "test#gmail.com",
"username": "Kirtan",
"password": "123213",
"creation_dt": "2020-04-06T14:21:40",
"__v": 0
}
Also as a side note, you had better to create unique indexes on username and email fields. This can be done applying unique: true option in the schema, but better to create these unique indexes at mongodb shell like this:
db.users.createIndex( { "email": 1 }, { unique: true } );
db.users.createIndex( { "username": 1 }, { unique: true } );
It's been awhile since I've done mongoose, but I'm pretty sure <model>.update() also actively updates the record in Mongo.
You use .update() when you want to update an existing record in Mongo, but you are instantiating a new User model (i.e. creating a new user)
try the following code instead for a NEW USER:
router.post('/newTask', isValidUser, (req, res) => {
addToDataBase(req,res)
})
async function addToDataBase(req, res) {
var dataa = {
pName: req.body.pName,
pTitle: req.body.pTitle,
pStartTime: req.body.pStartTime,
pEndTime: req.body.pEndTime,
pSessionTime: req.body.pSessionTime
}
// email field is already in `req.user`
var usr = new User({ ...req.user, tasks: [dataa] });
console.log(req.user.email);
try {
await usr.save();
return res.status(201).json(doc);
}
catch (err) {
return res.status(501).json(err);
}
}
Now, if you wanted to update an existing record :
router.post('/newTask', isValidUser, (req, res) => {
addToDataBase(req,res)
})
async function addToDataBase(req, res) {
var dataa = {
pName: req.body.pName,
pTitle: req.body.pTitle,
pStartTime: req.body.pStartTime,
pEndTime: req.body.pEndTime,
pSessionTime: req.body.pSessionTime
}
try {
await usr. updateOne({ email : req.user.email}, { $push: { tasks: dataa } });
return res.status(201).json(doc);
}
catch (err) {
return res.status(501).json(err);
}
}
For more info read: https://mongoosejs.com/docs/documents.html