Can't post to mongo db, "Error: ValidationError: name: Path `name` is required.," - insomnia

I am trying to post something to mongodb, my models file looks like this and i have input all of the required fields in insomnia but for some reason it's still not working.
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const contactSchema = new Schema({
name: { type: String, required: true },
email: { type: String, required: true },
phoneNumber: { type: Number, required: true },
message: { type: String, required: true },
date: { type: Date, required: false },
});
const Contact = mongoose.model('Contact', contactSchema);
module.exports = Contact;

Related

mongoose validator not working as expected

i want to add batch,department,stream,id fields to the schema depending if usertype is “Student”,i do not understand why,but sometimes it adds the fields sometimes not.forexample if i created a user with usertype “Student” first it does not add the fields,but after that when i created a user with usertype “Teacher” or “Admin” it asks me the fields are required meaning it add the fields and this happens vice versa.why any way to fix this issue?please help guys.
what i have tried well,i have asked chatGpt but no answers i mean just the answers do not solve the issue.
here is the code
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const userSchema = new Schema(
{
fullName: { type: String, required: true, unique: true },
email: { type: String, required: true, unique: true },
userType: {
type: String,
required: true,
},
phoneNumber: { type: String, required: true },
password: { type: String, required: true },
approved: { type: Boolean, default: true },
},
{
timestamps: true,
}
);
userSchema.pre("validate", function (next) {
if (this.userType === "Student") {
this.constructor.schema.add({
batch: {
type: Number,
required: true,
},
department: {
type: String,
required: true,
},
stream: {
type: String,
required: true,
},
id: { type: String, required: true }, //, unique: true
});
}
next();
});
const userModel = mongoose.model("users", userSchema);
module.exports = userModel;

Mongoose and MongoDB, how to create relation betwean two models with multiple references?

everyone.
So I have this "blog" app where users can create posts with images.
How my app works is that it loads different posts by userID.
So I have a relation bewtean user and post by the user and post _id, however I also want to save username into the post schema and created ralation that way. Is it possible to do such thing ?
This is my User schema
import mongoose from "mongoose";
import mongooseUniqueValidator from "mongoose-unique-validator";
const Schema = mongoose.Schema;
const validator = mongooseUniqueValidator;
const user_Schema = new Schema({
username: { type: String, required: true, unique: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true, minlength: 3 },
user_image: { type: String },
posts: [{ type: mongoose.Types.ObjectId, required: true, ref: 'Post' }], //relation bewtean post and user
},{ timestamps: true }
);
user_Schema.plugin(validator);
export const USER: mongoose.Model<any> = mongoose.model("User", user_Schema);
And this is my Post Schema:
import mongoose from "mongoose";
const Schema = mongoose.Schema;
const post_Schema = new Schema({
title: { type: String, required: true, },
description: { type: String, required: true, },
imageURL: { type: String },
creator_id: { type: mongoose.Types.ObjectId, required: true, ref: 'User' },
},
{ timestamps: true }
);
export const POST: mongoose.Model<any> = mongoose.model("Post", post_Schema);
However this is what I want the post to contain, I want the post to contain ID of the user who created it and the name of the user who created it.
However I do not know how to create it. So this is how I want my Post schema to look like, I want to be able to save both the user ID and username into the post.
const Schema = mongoose.Schema;
const post_Schema = new Schema({
title: { type: String, required: true, },
description: { type: String, required: true, },
imageURL: { type: String },
user: {
creator_id: { type: mongoose.Types.ObjectId, required: true, ref: 'User' }, //relation bewtean post and user
creator_name: { <soemthing here>, ref: 'User' }, //relation bewtean post and user
},
},
{ timestamps: true }
);
export const POST: mongoose.Model<any> = mongoose.model("Post", post_Schema);
If you want to retrieve the creator name using the ref is the correct approach, you just need to populate the Post documents when you are retrieving them with:
const posts = await Post.find({}).populate('creator').exec()
for (const post of posts) {
// Every post should contain the creator user properties
console.log(post.creator._id, post.creator.username)
}
Just make sure that your ref fields are of type mongoose.Schema.Types.ObjectId:
const post_Schema = new Schema(
{
title: { type: String, required: true },
description: { type: String, required: true },
imageURL: { type: String },
creator: { type: mongoose.Schema.Types.ObjectId, required: true, ref: 'User' },
},
{ timestamps: true }
);
export const POST: mongoose.Model<any> = mongoose.model('Post', post_Schema);

Subdocument not being saved in its own collection - Mongoose

I found this on the documentation for mongoose:
Subdocuments have save and validate middleware just like top-level
documents. Calling save() on the parent document triggers the save()
middleware for all its subdocuments, and the same for validate()
middleware.
But that hasn't been working for me. when I call save on my parent, the subdocument doesn't get created in its own collection. Here's my code:
Cart Model
const mongoose = require("mongoose");
const cartSchema = new mongoose.Schema({
numOfSessions: {
type: Number,
required: true
},
status:{
type: String,
enum: ["completed", "active", "deleted"],
required: true
}
}, { timestamps: true, versionKey: false });
const Cart = mongoose.model('shoppingCart', cartSchema);
module.exports = Cart;
User Model
const mongoose = require("mongoose");
const Cart = require("./xxxx").schema
const Schema = mongoose.Schema;
const userSchema = new Schema({
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
},
password: {
type: String,
required: true,
},
email: {
type: String,
required: true,
unique: true
},
shoppingCarts: [ Cart ]
}, { timestamps: true, versionKey: false });
const User = mongoose.model('user', userSchema);
module.exports = User;
Server Side
const new_user = new User({
firstName: req.body.firstname,
lastName: req.body.lastname,
username: req.body.username,
phoneNum: req.body.phone,
userType: req.body.userType,
email: req.body.email,
password: hashedPassword
});
new_user.shoppingCarts.push(new_cart);
console.log('pushed')
new_cart.save(); //If i take out this line, this subdocument doesn't get saved
new_user.save()
.then((result) => {
console.log(result);
});
To save the subdocument, I'm having to call save on it them well. Is this how it's supposed to be? Thx :D

Populate a property of a mongoose schema with all the data in another collection

I have a model with articles, and would like to populate an array of data with all the documents in a collection.
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ArticlesSchema = new mongoose.Schema({
path: {
type: String,
required: true,
unique: true,
},
base_headline: {
type: String,
required: true,
},
intro: {
type: String,
required: true,
},
featured_image: {
type: String,
required: true,
},
author: {
type: String,
required: true,
},
platform_filter: {
type: String,
},
free_filter: {
type: String,
},
content_type: {
type: String,
required: true,
},
data: [{ type: Schema.Types.ObjectId, ref: 'DesignProducts' }],
date: {
type: Date,
default: Date.now,
},
});
module.exports = mongoose.model('Articles', ArticlesSchema);
The data property should be populated with all documents in the DesignProducts collection.
I tried running this but the data array is still empty:
Article.findOne({ path: slug }).populate('data').exec();
Here is what the designProducts model looks like:
const mongoose = require('mongoose');
const DesignProductsSchema = new mongoose.Schema({
name: {
type: String,
required: true,
unique: true,
},
intro: {
type: String,
required: true,
},
website: {
type: String,
required: true,
},
date: {
type: Date,
default: Date.now,
},
});
module.exports = mongoose.model('DesignProducts', DesignProductsSchema);
This array should be populated with all the documents in the DesignProducts collection:

How create nested mongoDb schema in mongoose?

i'm trying to design mongoose shema for users cleaner and customer, they have some common fields e.g. name, but also have extra (different fields) client(rating) and customer number. I'm not sure that my design is good.
I've created separate userSchema for customer and cleaner, and created separate address schema.
// User Schema
const UserSchema = new mongoose.Schema({
name: {
type: String,
required: true
}
});
// AddressSchema
const AddressSchema = new mongoose.Schema({
city: {
type: String,
required: true
},
street: {
type: String,
required: true
}
});
// CustomerSchema
const CustomerSchema= new mongoose.Schema({
name: UserSchema,
address: AddressSchema
});
// CleanerSchema
const CleanerSchema= new mongoose.Schema({
name: UserSchema,
rating: {
type: Number,
required: true
}
});
My schema doesn't work. Could you give best practice example for my schema?
This is how I would define your Customer and Cleaner schemas. I don't think it's necessary to create the separate name and address schemas.
const CustomerSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
address: {
city: {
type: String,
required: true
},
street: {
type: String,
required: true
}
}
});
const CleanerSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
rating: {
type: Number,
required: true
}
});