The 2nd parameter to `mongoose.model()` should be a schema or a POJO - mongodb

I tried to launch my application. I don't even know which file causes this problem.
So say me which file i should show you.
Here is app.module.ts
import { Module } from '#nestjs/common';
import { ConfigModule } from '#nestjs/config';
import { AppController } from './app.controller';
import { AuthModule } from './auth/auth.module';
import { AssigmentsModule } from './posts/assigments.module';
import { UsersModule } from './users/users.module';
import { MongooseModule } from '#nestjs/mongoose';
#Module({
imports: [
ConfigModule.forRoot({
envFilePath: '.env',
isGlobal: true,
}),
MongooseModule.forRoot(process.env.MONGO_URI),
AuthModule,
AssigmentsModule,
UsersModule,
],
controllers: [AppController],
})
export class AppModule {}
And here is this repo look at dev branch.
https://github.com/MoneyIgos/biuro-makowskaj-api/tree/dev

I saw the your code on github, Maybe You have already figured it Out, I had the same problem few minutes back, this is How I solved
User Schema Looks Like this
export const UserSchema = new Schema({
username: { type: String, required: true },
password: { type: String, required: true },
});
const User = model<IUser>('User', UserSchema);
Assignment Schema Looks Like this
export const AssigmentSchema = new Schema({
title: { type: String, required: true },
description: { type: String, required: true },
image: { type: String, required: false },
createdAt: {
type: String,
default: () => new Date(),
},
});
const Assigment = model<IAssigment>('Assigment', AssigmentSchema);
In UserModule.ts
imports: [MongooseModule.forFeature([{ name: 'User', schema: UserSchema }])],
instead it should be
imports: [MongooseModule.forFeature([{ name: 'User', schema: User}])],
In AssignmentModule.ts
MongooseModule.forFeature([{ name: 'Assigment', schema: AssigmentSchema }]),
It should be like this
MongooseModule.forFeature([{ name: 'Assigment', schema: Assignment}]),

Related

How to add timestamps fields and _id into nested schema by default

I have a correct schema User where fields _id, createdAt, updatedAt are written by default. But in schema Message it doesn't work.
export type UserDocument = HydratedDocument<User>;
#Schema({ timestamps: true, versionKey: false })
export class Message {
#Prop()
content: string;
}
#Schema({ timestamps: true, versionKey: false })
export class User implements UserInterface {
#Prop()
name: string;
#Prop()
email: string;
#Prop([{ type: mongoose.Schema.Types.ObjectId, ref: 'Message' }])
messages?: Message[];
}
export const UserSchema = SchemaFactory.createForClass(User);
Here is my function of message creating:
async createMessage() {
const user = await this.userModel.findById('63ee4fc044d93a4f6bebf934');
user.messages.push({ content: 'a' });
return await user.save();
}
And error is:
Cast to ObjectId failed for value "{ content: 'a' }" (type Object) at path "messages" because of "BSONTypeError"
But this snippet works fine:
async createUser(createUserDto: CreateUserDto): Promise<CreatedUserDto> {
return this.userModel.findOneAndUpdate(
{ name: createUserDto.name },
createUserDto,
{ upsert: true, new: true },
);
}
How to fix it?
Fixed id, correct implementation:
import { Prop, Schema, SchemaFactory } from '#nestjs/mongoose';
import { HydratedDocument } from 'mongoose';
import { UserInterface } from '../interface/user.interface';
export type UserDocument = HydratedDocument<User>;
#Schema({ timestamps: true, versionKey: false })
export class Message {
#Prop()
content: string;
}
export const MessageSchema = SchemaFactory.createForClass(Message);
#Schema({ timestamps: true, versionKey: false })
export class User implements UserInterface {
#Prop()
name: string;
#Prop()
email: string;
#Prop({ type: [MessageSchema], default: [] })
messages?: Message[];
}
export const UserSchema = SchemaFactory.createForClass(User);

how to use nested object as a ref in mongoose

I have two schemas user and note-
user schema
import mongoose from 'mongoose';
const userSchema = mongoose.Schema({
id: {
type: String,
},
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
},
notes: [
{
type: mongoose.Types.ObjectId,
ref: 'Note',
},
],
folders: {
type: [
{
name: {
type: String,
},
notes: [
{
type: mongoose.Types.ObjectId,
ref: 'Note',
},
],
},
],
default: [
{ name: 'My Notes', notes: [] },
{ name: 'Todos', notes: [] },
{ name: 'Projects', notes: [] },
{ name: 'Journals', notes: [] },
{ name: 'Reading list', notes: [] },
],
},
});
const User = mongoose.model('User', userSchema);
export default User;
note schema
import mongoose from 'mongoose';
const noteSchema = new mongoose.Schema({
id: {
type: String,
required: true,
},
modify_date: {
type: String,
required: true,
},
modify_time: {
type: String,
required: true,
},
tags: [
{
id: {
type: String,
required: true,
},
text: {
type: String,
required: true,
},
},
],
created_by: {
type: mongoose.Types.ObjectId,
ref: 'User',
required: true,
},
folder: {
type: String, //can I use ref from user?
},
title: {
type: String,
},
body: {
type: String,
required: true,
},
time_stamp: {
type: Date,
required: true,
},
});
const Note = mongoose.model('Note', noteSchema);
export default Note;
I have searched but could not find anything. I want to use the nested folder object from user schema as a ref in note schema; so, whenever I change or update a folders name all the notes get the updated value. Is it possible?
If not should I make a separate folder schema and add ref of folder schema in both note and user? How can I achieve that, any suggestion might be very helpful?

MissingSchemaError: Schema hasn't been registered for model "Product"

------------------------------
Here is Order Controller
-----------------------------
import nc from "next-connect";
import db from "../../../utils/db";
import Order from "../../../models/OrderModel";
import { isAuth } from "../../../utils/auth";
const handler = nc();
handler.use(isAuth);
handler.get(async (req, res) => {
try {
await db.connect();
const order = await Order.findById(req.body.order).populate({
path: "product",
model: "Product",
});
await db.disconnect();
res.send(order);
} catch (err) {
console.log(err);
}
});
export default handler;
--------------------------------------------------------------
Here is Order Schema
--------------------------------------------------------------
import mongoose from "mongoose";
const orderSchema = new mongoose.Schema(
{
product: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Product",
required: true,
},
],
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
required: true,
}
},
{ timestamps: true }
);
const Order = mongoose.models.Order || mongoose.model("Order", orderSchema);
export default Order;
----------------------------
Here is Product Schema
----------------------------
import mongoose from "mongoose";
const productSchema = new mongoose.Schema(
{
name: {
type: String,
required: true,
},
description: {
type: String,
required: true,
},
price: {
type: Number,
required: true,
},
category: {
type: String,
required: true,
},
period: {
type: String,
required: true,
},
features: [{ type: String, required: true }],
},
{ timestamps: true }
);
const Product =
mongoose.models.Product || mongoose.model("Product", productSchema);
export default Product;
--------------------
I am getting this error: "MissingSchemaError: Schema hasn't been registered for model "Product".
Use mongoose.model(name, schema)"
There are also some orders including product ObjectId and I am trying to get the data using populate on the POSTMAN but getting this error.
I've really searched much before posting this but I've didn't solve the error

MongoDb aggregate query, how to select field from foreign table?

I am running a mongoDb query trying to get the data of my "User" which also include the "CounterParty.name" My aggregate query does get the user back, but does nothing with the fields from Counterparty. I went through the docs several times but cannot seem to figure it out.
My UserSchema
import { Schema, model } from "mongoose";
import mongoose from "mongoose";
export type UserDocument = mongoose.Document & {
email: string;
password: string;
status: string;
name: string;
counterParty: Schema.Types.ObjectId;
}
const userSchema = new Schema<UserDocument>(
{
email: {
type: String,
required: true
},
password: {
type: String,
required: true
},
name: {
type: String,
required: true
},
status: {
type: String,
default: "I am new"
},
counterParty: {
type: Schema.Types.ObjectId,
ref: "CounterParty",
}
},
{ timestamps: true }
)
export const User = model<UserDocument>('User', userSchema);
My CounterPartySchema
import { Schema, model } from "mongoose";
import mongoose from "mongoose";
export type CounterPartyDocument = mongoose.Document & {
name: string
}
const counterPartySchema = new Schema<CounterPartyDocument>(
{
name: {
type: String,
required: true,
unique: true,
trim: true
},
},
{ timestamps: true }
)
export const CounterParty = model<CounterPartyDocument>('CounterParty', counterPartySchema);
My query code
const user = await User.aggregate<any>([
{ '$match': { email: email } },
{
'$lookup': {
from: 'CounterParty',
localField: 'counterParty',
foreignField: '_id',
as: 'details'
}
}
])
console.log("user", user)
My console log statement now returns the user, but nothing to see of the counterParty.
Any help will be much appreciates! Cheers
Your aggregation query looks fine in the playground , maybe you dont have such _id: new ObjectId("...786") in the counterParty collection?

MissingSchemaError in Nestjs

hello everyone i'm not able specify relation to another model. when i add a relation it's showing me this error
Book Model
import { Prop, Schema, SchemaFactory } from '#nestjs/mongoose';
import { Document } from 'mongoose';
export type BookDocument = Book & Document;
#Schema({ timestamps: true, collection: 'books' })
export class Book {
#Prop({ type: String, required: true })
name: string;
#Prop({ type: String, required: true })
author: string;
#Prop({ type: String, required: true })
bookType: string;
}
export const BooksSchema = SchemaFactory.createForClass(Book);
BookLend Model
import { Prop, Schema, SchemaFactory } from '#nestjs/mongoose';
import { Schema as mongooseSchema, Document } from 'mongoose';
import { Book } from '../../books/enitiy/book.model';
import { IsNotEmpty } from 'class-validator';
export type BookLendDocument = BookLend & Document;
#Schema({ timestamps: true })
export class BookLend {
#IsNotEmpty()
#Prop({ type: mongooseSchema.Types.ObjectId, ref: 'books', required: true })
bookId: Book;
#IsNotEmpty()
#Prop({ type: String, required: true })
name: string;
#IsNotEmpty()
#Prop({ type: String, required: true })
returnDate: string;
#Prop({ type: String })
returnedOn: string;
#IsNotEmpty()
#Prop({ type: String, required: true })
status: string;
}
export const BookLendSchema = SchemaFactory.createForClass(BookLend);
i'm referring the books objectID to booklend booksID , when i use below code i'm getting error MissingSchemaError: Schema hasn't been registered for model "books".
const allBookLendDetails = await this.bookLend
.find()
.populate('bookId')
.exec();
hi guy's I fixed it by importing the BooksSchema into BookLend Module file
here ref code:-
import { Module } from '#nestjs/common';
import { BookLendService } from './book-lend.service';
import { BookLendController } from './book-lend.controller';
import { MongooseModule } from '#nestjs/mongoose';
import { BookLendSchema } from './entities/book-lend.entity';
import { CommonService } from '../common-service/common-service.service';
import { BooksSchema } from '../books/enitiy/book.model';
#Module({
imports: [
MongooseModule.forFeature([
{ name: 'booklend', schema: BookLendSchema },
{ name: 'books', schema: BooksSchema },
]),
],
controllers: [BookLendController],
providers: [BookLendService, CommonService],
})
export class BookLendModule {}
In the service file, you need to inject the model
constructor(
#InjectModel('booklend') private readonly bookLend: Model<BookLend>,
#InjectModel('books') private readonly books: Model<Book>
) {}