const mongoose = require("mongoose");
const PostSchema = new mongoose.Schema(
{
user_id: {
type: String,
required: true,
},
content: {
type: String,
max: 150,
required: true,
},
},
{
timestamps: true,
}
);
As defined above, I can nevertheless push content that has more than 150 characters. What is wrong with how the Query is defined?
Type string does not have “max”, instead use “maxLength”:
maxLength: 150,
Documentation about validation that mentions this.
Hopefully that helps!
Related
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
//broken schema
var coursesSchema = new Schema({
college: {
type: String,
required: true
},
units: {
type: Number,
required: true
},
course_code: {
type: String,
required: true
},
course_name: {
type: String,
required: true
},
class_number: {
type: String,
required: true
},
section: {
type: String,
required: true
},
class_day: {
type: String,
required: true
},
time_start: {
type: String,
required: true
},
time_end: {
type: String,
required: true
},
faculty: {
type: String,
required: true
}
});
module.exports = mongoose.model('Courses', coursesSchema);
//working schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var loaSchema = new Schema({
process_name: {
type: String,
required: true
},
process_details: {
type: String,
required: true
},
process_deadline: {
type: String,
required: true
},
});
module.exports = mongoose.model('LOA', loaSchema);
I have this schema which I export into index.js file. This schema works in other parts of the code except in index.js. When I query Courses schema, it returns model.find() is not a function. When I try creating a new Courses object it says Constructor is not a schema. I have other schemas that work fine inside index.js and I get to query them, but this schema is an exception.
Does anyone know the reason behind this?
index.js is the special file and actually it's root of your module, it's better separate the schema from that to prevent from bugs
I am getting this error and can't figure it out. I HAVE NAMED THE REF EXACLTY AS THE MODEL:
MissingSchemaError: Schema hasn't been registered for model "ParticipantStatus".
Here are my models:
ParticipantStatus model:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const participantStatusSchema = new Schema({
_id: {
type: Number,
required: true,
},
name: {
type: String,
required: true,
},
});
module.exports = mongoose.model('ParticipantStatus', participantStatusSchema);
EventParticipant model:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const eventParticipantSchema = new Schema(
{
userId: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true,
},
eventId: {
type: Schema.Types.ObjectId,
ref: 'Event',
required: true,
},
teamId: {
type: Schema.Types.ObjectId,
ref: 'Team',
},
statusId: {
type: Number,
ref: 'ParticipantStatus',
required: true,
},
isActive: {
type: Boolean,
required: true,
default: true,
},
},
{ timestamps: true }
);
module.exports = mongoose.model('EventParticipant', eventParticipantSchema);
This is the code where the error is thrown, when i try to get event participants and populate statusId(ParticipantStatus):
let participants = await EventParticipant.find(
{
eventId: req.params.eventId,
isActive: true,
},
{ _id: false }
)
.populate('userId', 'email')
.populate('statusId')
.select('userId');
I have been stuck for hours on this. Only the .populate('statusId') part throws the error, the rest works well. Thanks in advance
type of field that you want to populate based on should be ObjectId so change the type of statusId from Number to Schema.Types.ObjectId like this:
statusId: {
type: Schema.Types.ObjectId,
ref: 'ParticipantStatus',
required: true,
}
Well the problem was that u need to import:
const ParticipantStatus = require('../models/participantStatus.model');
even if you do not REFERENCE IT DIRECTLY in your code, which is really strange in my opinion.
Hope this helps anyone.
Let's say I have these two models below and i want to get or fetch the location of a specific user using mongoose in node:
User Model
const userSchema = new mongoose.Schema({
name: {
type: String,
minlength: 2,
maxlength: 50,
},
email: {
type: String,
minlength: 5,
maxlength: 255,
unique: true,
},
password: {
type: String,
minlength: 5,
maxlength: 1024,
},
});
And Location Model
const locationtSchema = new mongoose.Schema({
name: {
type: String,
minlength: 5,
maxlength: 50,
},
lat: {
type: String,
required: true,
},
lng: {
type: String,
required: true,
},
user: {
type: userSchema,
required: true,
},
});
So, I tried to resolve it like this... but it didn't work.
const location = Location.find({
'user._id': req.params._id
})
How can i return locaitons of a specific user?
The id you are trying to pass is a string, instead, it should be an object id
const location = Location.find({
'user._id': mongoose.Types.ObjectId(req.params._id)
})
It would work perfectly now.
I have two same functions, first saves some stuff and also saves ref to productId and second saves another stuff and saves ref to productId too. The problem is first writes ref to poductId as object and everything is ok but second function saves ref as string and in mongodb i see ObjectId but when im trying to display data on screen i cant access into object i have only string with ID of refer. Any ideas?
first model which is ok
const mongoose = require('mongoose')
const dishPositionsSchema = mongoose.Schema({
productId: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'Products'
},
dishId: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'Dishes'
},
weight: {
type: Number,
required: true
}
})
module.exports = mongoose.model('DishPositions', dishPositionsSchema)
and second which stores only strings instead of objects
const mongoose = require('mongoose')
const diaryPositionsSchema = mongoose.Schema({
productId: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'Products'
},
dishId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Dishes'
},
weight: {
type: Number,
required: true,
required: true
},
timeOfEatingId: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'TimeOfEating'
},
date: {
type: String,
required: true
}
})
module.exports = mongoose.model('DiaryPositions', diaryPositionsSchema)
I know where i did mistake... i didnt write populate('productId')... everything is fine now thanks!
Here is my code. I have a review schema in a separate file called "review.js".
const express = require('express');
const mongoose = require('mongoose');
const User = require('../model/user');
require('mongoose-currency').loadType(mongoose);
const Currency = mongoose.Types.Currency;
const Schema = mongoose.Schema;
let reviewSchema = new Schema();
reviewSchema.add({
rating: {
type: Number,
min: 1,
max: 5,
defualt: 0
},
howEasyToMake: {
type: Number,
required: true,
min: 1,
max: 5
},
howGoodTaste: {
type: Number,
required: true,
min: 1,
max: 5,
},
wouldMakeAgain: {
type: Number,
required: true,
min: 1,
max: 5,
},
comment: {
type: String,
default: ""
},
postedBy: {
type: String,
required: true,
index: true
},
reviewOf: {
type: String,
required: true,
index: true
},
postersCreationDate: {
type: Number,
required: true
},
chefsCreationDate: {
type: Number,
required: true
},
chefsId: {
type: String,
required: true
}
});
module.exports.reviewSchema = reviewSchema;
I have another file called recipe.js, where I import reviewSchema and use it as an embedded schema for my Recipe model schema.
const express = require('express');
const mongoose = require('mongoose');
const User = require('../model/user');
require('mongoose-currency').loadType(mongoose);
const Currency = mongoose.Types.Currency;
const Schema = mongoose.Schema;
const reviewSchema = require('../model/review').reviewSchema;
let recipeSchema = new Schema({
name: {
type: String,
required: true
},
description: {
type: String,
},
steps: {
type: String,
required: true,
},
ingredients: {
type: Array,
default: ['1', '2', '3', '4']
},
category: {
type: String,
required: true,
index: true
},
postedBy: {
type: String,
required: true,
},
reviewsOfRecipe: [reviewSchema],
numberOfRatings: {
type: Number,
default: 0
},
totalAddedRatings: {
type: Number,
default: 0
},
reviewAverage: {
type: Number,
default: undefined
},
postersCreationDate: {
type: Number,
index: true
},
likedBy: {
type: Array
},
reviewedBy: {
type: Array
}
});
recipeSchema.methods.updateReviewAverage = function(){
let recipe = this;
this.reviewAverage = this.totalAddedRatings / this.numberOfRatings;
};
let Recipe = mongoose.model('Recipe', recipeSchema);
module.exports = Recipe;
I have another file called recipeRouter.js where I use reviewSchema to construct a review to then later insert it into the embedded reviewsOfRecipes array in my Recipe document. In my recipRouter.js file, every time my code tries to do this....
Recipe.findOne({name: req.params.name}).then((recipe) => {
let review_ = new reviewSchema({
comment: req.body.comment
rating: req.body.score
});
recipe.reviewsOfRecipe.push(review_);
})
...I get this error.
TypeError: reviewSchema is not a constructor
Previously, when I ran into this problem, I had the reviewSchema in the same file as my Recipe model schema. Since then, I split the two into each having their own file. And I made sure to properly export module.exports.reviewSchema = reviewSchema; in my review.js file, and made sure to have const reviewSchema = require('../model/review').reviewSchema; in both my recipe.js and recipeRouter.js files. Yet still this issue still comes up/ I would greatly appreciate it if someone could point out what may be the issue.
You have to export reviewSchema like you did to the other schema (using mongoose.model):
module.exports.reviewSchema = mongoose.model('Review', reviewSchema);