Mongoosejs Validation Errors - node.js

I'm unable to get my data to go into my MongoDB collection. It gives me this message:
Here's the Schema. I'm able to make GET, PATCH, AND DELETE work but not POST. I've tried looking up the answers in regards to this issue, however, the support doesn't look stellar. I
const IssueSchema = new mongoose.Schema({
projectTitle: {
type: String,
required: [true, 'must provide project title'],
trim: true,
maxLength: [30, 'project name cannot be more than 30 characters']
},
completed: {
type: Boolean,
default: false
},
description: {
type: String,
required: [true, 'must provide a succinct description of the project'],
trim: true,
maxLength: [120, 'project description cannot be more than 120 characters']
},
createdAt: {
type: Date,
default: Date.now()
},
issueTitle: {
type: String,
required: [true, 'must provide issue title'],
trim: true,
maxLength: [30, 'project name cannot be more than 30 characters']
},
priority: {
type: String,
enum: {
values: ['low', 'normal', 'important', 'critical'],
message: `{VALUE} is not supported`
}
},
issuer: {
type: String,
enum: {
values: ['Admin', 'Lead', 'QA'],
message: `{VALUE} is not supported`
}
},
developer: {
type: String,
enum: {
values: ['Jason W.', 'Ada L.', 'Alan T.'],
message: `{VALUE} is not supported`
}
},
status: {
type: String,
enum: {
values: ['open', 'closed'],
message: `{VALUE} is not supported`
}
},
type: {
type: String,
trim: true
}
})
module.exports = mongoose.model('Issue', IssueSchema)```

Related

getting a mongoose error while connecting this to controller

const mongoose = require('mongoose');
const productSchema = new mongoose.Schema({
name: {
type: String,
required: [true,'Please Enter Product Name'],
trim:true,
maxLength: [100, 'Product Name Cannot Exeed 100 Characters']
},
price: {
type: Number,
required: [true,'Please Enter Product Price'],
maxLength: [5, 'Product Price Cannot Exeed 5 Characters']
},
description: {
type: String,
required: [true,'Please Enter Product Description'],
},
ratings: {
type: Number,
default: 0
},
images: [
{
public_id: {
type:String,
required: true
},
url:{
typr:String,
required: true
}
}
],
category: {
typr: String,
required: [true, 'Please select category for this Product'],
enum: {
values: [
'Electronics',
'Camera',
'Laptop',
'Accessories',
'HeadPhones',
'Food',
'Books',
'Clothes/Shoes',
'Beauty/Health',
'Sports',
'Outdoor',
'Home'
],
required: [true, 'Please Select correct category for product']
}
},
seller: {
type: String,
required: [true, 'Please enter product seller']
},
stock: {
type: Number,
required: [true, 'Please enter Product stock number'],
maxlength:[5, 'Product name connot exceed 5 characters'],
default: 0
},
numOfReviews: {
type: Number,
default: 0
},
reviews:[
{
name: {
type: String,
required: true
},
rating: {
type: Number,
required: true
},
comment: {
type: String,
required: true
}
}
],
createdAt: {
type: Date,
default: Date.now
}
})
module.exports = mongoose.model('Product',productSchema);
can you check type spelling in your code. You used typr instead of type
So, it is throwing TypeError: Invalid schema configuration: True is not a valid type at path url.required.
One of those line are:
url:{
typr:String,
required: true
}
You have to use the line as:
url:{
type:String,
required: true
}
Make sure spelling mistakes.

$Geonear does not work in the aggregation pipeline

I've got a tour collection with the following model:
const tourSchema = new mongoose.Schema(
{
slug: {
type: String,
},
name: {
type: String,
required: ['true', 'a tour must have a name'],
unique: true,
trim: true,
maxlength: [40, 'a tour name must not be more than 40 characters'],
minlength: [10, 'a tour must not be less than 10 characters'],
// validate: [validator.isAlpha, 'name should only contain A-Z'],
},
duration: {
type: Number,
required: [true, 'a tour must have a duration'],
},
maxGroupSize: {
type: Number,
required: [true, 'a tour must have a group size'],
},
difficulty: {
type: String,
required: [true, 'a tour should have a difficulty'],
enum: {
values: ['easy', 'medium', 'difficult'],
message: 'Difficulty is either easy, medium or difficult',
},
},
ratingsAverage: {
type: Number,
default: 4.5,
min: [1, 'Rating must be more than 1'],
max: [5, 'Maximum rating is 5'],
set: (val) => Math.round(val * 10) / 10,
},
ratingsQuantity: {
type: Number,
default: 0,
},
price: {
type: Number,
required: ['true', 'a tour must have a price'],
},
priceDiscount: {
type: Number,
validate: {
validator: function (val) {
// this only points to current doc on NEW document creation
return val < this.price;
},
message: 'Discount price {VALUE} should be lower than regualr price',
},
},
summary: {
type: String,
trim: true,
required: ['true', 'a tour must have a description'],
},
description: {
type: String,
trim: true,
},
imageCover: {
type: String,
required: ['true, a tour must have a cover image'],
},
images: [String],
createdAt: {
type: Date,
default: Date.now(),
select: false,
},
startDates: [Date],
secretTour: {
type: Boolean,
default: false,
},
startLocation: {
// GEOJSON
type: {
type: String,
default: 'Point',
enum: ['Point'],
},
coordinates: [Number],
address: String,
description: String,
},
locations: [
{
type: {
type: String,
default: 'Point',
enum: ['Point'],
},
coordinates: [Number],
address: String,
description: String,
day: Number,
},
],
guides: [{ type: mongoose.Schema.ObjectId, ref: 'User' }],
},
{
toJSON: { virtuals: true },
toObject: { virtuals: true },
}
);
I've written an aggregate of type $GeoNear like this:
const distances = await Tour.aggregate([
{
$geoNear: {
near: {
type: 'Point',
coordinates: [lng * 1, lat * 1],
},
distanceField: 'distance',
distanceMultiplier: multiplier,
},
},
]);
I've read the official documentation, and everything else that I could find online, left no stone upturned.
I'm aware that I should have a '2dSphere' index. And it exists on my mongoDB. I've also made sure that this is the first aggregation in the pipeline.
However the results are always empty! this is so frustrating! could be because of this https://github.com/parse-community/parse-server/pull/6540. Any opinion is much appreciated.

MongoDB collection fields not showing in same order as they are in model schema

I am creating some REST api's using mongodb, nodejs and express, and I have user model schema. The way fields are in the user model, after saving the document in mongodb they are not appearing in the same format as they are in the model.
As i am new to mongoDB and nodejs I don't have much idea what to do and the fields are saving in this way, is there anything i can do?
User Model -
const UserSchema = new mongoose.Schema({
_id: {
type: String,
default: () => (new mongoose.Types.ObjectId()).toString()
},
name: {
type: String,
required: true,
minlength: 5,
maxlength: 50
},
email: {
type: String,
required: true,
minlength: 5,
maxlength: 255,
unique: true
},
password: {
type: String,
required: true,
minlength: 5,
maxlength: 1024
},
isVerified: {
type: Boolean,
default: false
},
role: {
type: String,
default: 'pet owner',
enum: ["pet owner", "employee", "admin"]
},
status : {
type: String,
default: 'active',
enum: ['active', 'inactive']
},
phoneNumber: {
type: Number,
default: null
},
countryCode: {
type: String,
default: null
},
dialCode: {
type: String,
default: null
},
birthday: {
type: Date,
default: null
},
address: {
type: String,
default: null
},
state: {
type: String,
default: null
},
city: {
type: String,
default: null
},
pincode: {
type: Number,
default: null
},
information: {
type: String,
default: null
},
resetPasswordToken: {
type: String,
required: false
},
resetPasswordExpires: {
type: Date,
required: false
},
createdAt: {
type: Date,
default: null
},
updatedAt: {
type: Date,
default: null
}
});
After Save -
_id:"5e7c68c08373c5313b104c0a"
isVerified:true
role:"pet owner"
status:"active"
phoneNumber:null
countryCode:null
dialCode:null
birthday:null
address:null
state:null
city:null
pincode:null
information:null
createdAt:2020-03-26 14:03:04.312
updatedAt:null
name:"rahul kundu"
email:"rahul.kundu#massoftind.com"
password:"$2a$10$bHrQA6UXVKmfy4eYQfe1C.dJ6Xj7xUiBWzj90jc9X2npPCfGYEElK"
__v:0

Mongoose model seperations

Im new to node and mongodb. I have the following mongoose model.
import { model, Schema } from 'mongoose';
import Joi from '#hapi/joi';
const profileSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: 'users',
},
handle: {
type: String,
minlength: 2,
maxlength: 20,
required: true,
trim: true,
},
company: {
type: String,
minlength: 1,
maxlength: 100,
trim: true,
},
website: {
type: String,
maxlength: 100,
trim: true,
},
location: {
type: String,
maxlength: 100,
trim: true,
},
status: {
type: String,
maxlength: 50,
trim: true,
required: true,
},
skills: {
type: [String],
required: true,
},
bio: {
type: String,
maxlength: 500,
trim: true,
},
githubUserName: {
type: String,
maxlength: 50,
trim: true,
},
experience: [
{
title: {
type: String,
maxlength: 100,
trim: true,
required: true,
},
company: {
type: String,
maxlength: 100,
trim: true,
required: true,
},
location: {
type: String,
maxlength: 100,
trim: true,
required: true,
},
from: {
type: Date,
required: true,
},
to: {
type: Date,
},
current: {
type: Boolean,
default: false,
},
description: {
type: String,
maxlength: 500,
trim: true,
},
},
],
education: [
{
school: {
type: String,
maxlength: 100,
trim: true,
required: true,
},
degree: {
type: String,
maxlength: 100,
trim: true,
required: true,
},
fieldOfStudy: {
type: String,
maxlength: 100,
trim: true,
required: true,
},
from: {
type: Date,
required: true,
},
to: {
type: Date,
},
current: {
type: Boolean,
default: false,
},
description: {
type: String,
maxlength: 500,
trim: true,
},
},
],
social: {
youtube: {
type: String,
maxlength: 100,
trim: true,
},
twitter: {
type: String,
maxlength: 100,
trim: true,
},
facebook: {
type: String,
maxlength: 100,
trim: true,
},
linkedin: {
type: String,
maxlength: 100,
trim: true,
},
instagram: {
type: String,
maxlength: 100,
trim: true,
},
},
date: {
type: Date,
default: Date.now,
},
});
export default model('profile', profileSchema);
I have created this model in a single file and it seems too big. So should I put experience, education and social into 3 seperate models? If so how should I do it? If I put these in to 3 seperate models, how can I link them with the profile model? An example would be highly appriciated.
Yes, you should seperate them. To link them you would just put the profile schema Id as a field on the other models.
const profileSchema = new Schema({
userId: Schema.Types.ObjectId
})
const experienceSchema = new Schema({
userId: Schema.Types.ObjectId
})
const educationSchema = new Schema({
userId: Schema.Types.ObjectId
})
Then you would just query the experience collection by the userId to get their experiences. This is the way I'd recommend.
Another way wouldbe to put experienceIds on the profile schema that would reference the Experience model and could use the populate method to fill the fields.

Error: Can't set headers after they are sent on post request, why?

Any time I added validation from my schema and try to make a post request I get the following error message:
Error: Can't set headers after they are sent.
var PlayerSchema = new Schema({
firstName: { type: String, require: true, required: 'First Name is required' },
lastName: { type: String, require: true, required: 'Last Name is required' },
nickName: { type: String, trim: true },
mentor: { type: String, trim: true },
clubName: { type: String, trim: true },
created_at: { type: Date, default: Date.now },
updated_at: { type: Date, default: Date.now },
email: {
type: String,
trim: true,
unique: true,
required: 'Email address is required',
validate: [validateEmail, 'Please fill a valid email address'],
match: [/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/, 'Please fill a valid email address']
},
phoneNumber: {
type: String,
unique: true,
required: 'Phone Number is required',
}
});

Resources