Mongoose Schema cannot be identified by code - javascript

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

Related

Mongoose getting the error: MissingSchemaError: Schema hasn't been registered for model

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.

can a mongoose schema field reference more than one other models

I have a mongoose schema field called "bookmarks" and I would like it to reference more than one model. for example, if I have 2 other models named "post" and "complain". I would like the user to be able to bookmark both of them.
const userSchema = new mongoose.Schema({
fullname: {
type: String,
required: true,
trim: true,
lowercase: true
},
username: {
type: String,
unique: true,
required: true,
trim: true,
lowercase: true
},
email: {
type: String,
unique: true,
required: true,
trim: true,
lowercase: true,
validate(value) {
if (!validator.isEmail(value)) {
throw new Error('Email is invalid')
}
}
},
bookmarks: [{
type: mongoose.Schema.Types.ObjectId,
required: false,
ref: 'Post'
}],
})
below is a post model, where users can post things in general
const postSchema = new mongoose.Schema({
body: {
type: String,
required: true,
trim: true,
lowercase: true
}
})
below is a complain model, where users can post a complain
const complainSchema = new mongoose.Schema({
body: {
type: String,
required: true,
trim: true,
lowercase: true
}
})
How can I get the bookmarks field in the user model to be able to get the object id of both the complain model and the post model?
You can nest those two models in userSchema itself just like you are doing with bookmark schema .
You can also refer to this link , i hope it will resolve your query.
Link - : What is the proper pattern for nested schemas in Mongoose/MongoDB?
Here is the correct way to achieve this.
First remove bookmarks
Add this
ref: {
kind: String, // <-- Model Name post,complain
item: {
type: mongoose.Schema.Types.ObjectId,
refPath: 'ref.kind',
fields: String,
},
},
When you want to fetch the records,you can use populate
model.User.find({})
.populate({ path: 'ref.item' })
.then(data=>{console.log(data)})
.catch(err => {console.log(err)});

Node mongodb stores data as string instead of an object

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!

Adding new object array to a spesific id, but it creates a new row

I need to push new objects to my products array. I found out that findOneAndUpdate() method works for the first time if the array is empty. When I do a save() method, it creates a seperate row with only the products. I've tried everythig to my knowledge without success.
My Schemas;
const ProdcutSchema = new mongoose.Schema({
name:{
type: String,
required: true
},
productDescription:{
type: String,
required: true
},
pricePerUnit:{
type: Number,
required: true
},
productAmmount:{
type:Number,
required: true
},
/*productImagePath:{
type:String,
required: true
}*/
});
const UserSchema = new mongoose.Schema({
name:{
type: String,
required: true
},
email:{
type: String,
required: true
},
password:{
type: String,
required: true
},
date:{
type: Date,
default: Date.now
},
products:[ProdcutSchema]
});
const User = mongoose.model('User', UserSchema);
module.exports = User;
Mongoose ran on POST method:
const newProduct = new User({
email: useremail,
products:[{
name :product_name,
productDescription : product_Description,
pricePerUnit : price_PerUnit,
productAmmount : product_Ammount
}]
});
newProduct.save((err)=>{
if(err) console.log(err);
res.redirect('/dashboard');
});
In your case, i think you should use $push operator.
Example:
await User.findOneAndUpdate(your_condition, {$push: {products: your_new_product}});

MongoDB Chat Schema

Im trying MongoDB and as a matter of starting point im creating a schema for a chat application that may be simple to scale in the future, so im wondering if this looks correct from what i have been seeing in the docs. So far i have 3 collections User, Room, Message. Also i would need to perform some queries like getting all messages from a sepecific room, get all messages from a specific user, etc
Designed with mongoose:
var user = new mongoose.Schema({
username: { type: String, lowercase: true, unique: true },
email: { type: String, lowercase: true, unique: true },
password: String,
is_active: { type: Boolean, default: false },
});
var room = new mongoose.Schema({
name: { type: String, lowercase: true, unique: true },
topic: String,
users: [user],
messages: [message],
created_at: Date,
updated_at: { type: Date, default: Date.now },
});
var message = new mongoose.Schema({
room: room,
user: user,
message_line: String,
created_at: { type: Date, default: Date.now },
});
var User = mongoose.model('User', user);
var Room = mongoose.model('Room', room);
var Message = mongoose.model('Message', message);
//message model
'use strict';
import mongoose from 'mongoose';
var Schema = mongoose.Schema;
var ObjectId = Schema.Types.ObjectId;
var MessageSchema = new Schema({
send: {
type: ObjectId,
ref: 'User',
required: true
},
message: {
type: String,
required: true
},
date: {
type: Date
},
created_by: {
type: ObjectId,
ref: 'User',
required: true
},
thread: {
type: ObjectId,
ref: 'MsgThread',
required: true
},
is_deleted: [{
type: ObjectId,
ref: 'User'
}]
}, {
timestamps: {
createdAt: 'created_at',
updatedAt: 'last_updated_at'
}
});
export default mongoose.model('Message', MessageSchema);
//dont use rooms,,use thread like groupchat or personalChat
import mongoose from 'mongoose';
var Schema = mongoose.Schema;
var ObjectId = Schema.Types.ObjectId;
const s3 = require("../../utils/s3");
var MsgThreadSchema = new Schema({
users: [{
type: ObjectId,
ref: 'User'
}],
group_name: {
type: String
},
created_by: {
type: ObjectId,
ref: 'User'
},
community: {
type: ObjectId,
ref: 'Community'
},
image_url: {
type: String
}
}, {
timestamps: {
createdAt: 'created_at',
updatedAt: 'last_updated_at'
}
});
export default mongoose.model('MsgThread', MsgThreadSchema);

Categories

Resources