I have created a nodejs backend project with mongodb as the database. I want to create a document where it stores details of multiple students. Below shows my controller and model files.
Controller.js
const _user = new User({
username: req.body.username,
role: req.body.role,
hash_password: hash_password,
re_hash_password: req.body.re_hash_password,
student:{
member1: {
fullName: req.body.student.member1.fullName,
sliit_id: req.body.student.member1.sliit_id,
phone: req.body.student.member1.phone,
email: req.body.student.member1.email,
specialization: req.body.student.member1.specialization,
},
member2: {
fullName: req.body.student.member2.fullName,
sliit_id: req.body.student.member2.sliit_id,
phone: req.body.student.member2.phone,
email: req.body.student.member2..email,
specialization: req.body.student.member2.specialization,
},
}
Above shows the controller of my nodejs project. Here I want to add multiple members to my mongodb database with student object.
Model.js
const demoStudentSchema = new mongoose.Schema({
fullName: {
type: String,
required: true,
trim: true,
min: 3,
max: 30
},
sliit_id: {
type: String,
required: true,
trim: true,
min: 3,
max: 20
},
phone: {
type: String,
required: true
},
email: {
type: String,
required: true,
trim: true,
unique: true,
lowercase: true
},
specialization: {
type: String,
enum: ['SE','CSNE','DS', 'ISE', 'CS']
},
})
const userSchema = new mongoose.Schema({
username: {
type: String,
required: true,
trim: true,
unique: true,
index: true,
min: 3,
max: 20
},
role: {
type: String,
required:true,
enum: ['student','supervisor','staff']
},
hash_password: {
type: String,
required: true,
},
re_hash_password: {
type: String,
required: true,
},
student: {
member1: {
demoStudentSchema
},
member2: {
demoStudentSchema
}
}
When I try to run this code using postman, below error occurs.
Postman request and error
{
"message": {
"errors": {
"email": {
"name": "ValidatorError",
"message": "Path `email` is required.",
"properties": {
"message": "Path `email` is required.",
"type": "required",
"path": "email"
},
"kind": "required",
"path": "email"
},
"phone": {
"name": "ValidatorError",
"message": "Path `phone` is required.",
"properties": {
"message": "Path `phone` is required.",
"type": "required",
"path": "phone"
},
"kind": "required",
"path": "phone"
},
"sliit_id": {
"name": "ValidatorError",
"message": "Path `sliit_id` is required.",
"properties": {
"message": "Path `sliit_id` is required.",
"type": "required",
"path": "sliit_id"
},
"kind": "required",
"path": "sliit_id"
},
"fullName": {
"name": "ValidatorError",
"message": "Path `fullName` is required.",
"properties": {
"message": "Path `fullName` is required.",
"type": "required",
"path": "fullName"
},
"kind": "required",
"path": "fullName"
}
},
"_message": "User validation failed",
"name": "ValidationError",
"message": "User validation failed: email: Path `email` is required., phone: Path `phone` is required., sliit_id: Path `sliit_id` is required., fullName: Path `fullName` is required."
}
}
I have gone through some videos and articles but couldnt find out any solution.
Could you please help me to find out the error and give your suggestions on solving this issue.
Related
I have a Mongoose Schema ready but when I call it with my api it gives out validation errors in all of the required fields
this is my schema object
const userSchema = new mongoose.Schema({
name: {
type: String,
required: [true, 'Please use a name']
},
email: {
type: String,
required: [true, 'Please use a valid e-mail'],
unique : true,
lowercase: true,
validator: [validator.isEmail, 'Please provide a valid e-mail']
},
password: {
type: String,
required: [true, 'Please provide a password for your profile'],
minlength: 6
},
passwordConfirm: {
type: String,
required: [true, 'Please confirm your password']
}
})
const User = mongoose.model('User', userSchema)
the req. body i sent with the api through JSON is
{
"name": "user1",
"email": "user1#gmail.com",
"password": "pass1234",
"passwordConfirm": "pass1234"
}
I was trying to make a new user through the api and model throuth the controller
exports.signup = async (req, res, next) => {
try {
const newUser = await User.create(req.body)
console.log('in the newUser');
res.status(201)
.json({
status: 'success',
data: {
user: newUser
}
})
}catch (err){
res.status(400).json({
status: 'fail',
message: err
})
}
}
then I get the following errors in postman
{
"status": "fail",
"message": {
"errors": {
"passwordConfirm": {
"name": "ValidatorError",
"message": "Please confirm your password",
"properties": {
"message": "Please confirm your password",
"type": "required",
"path": "passwordConfirm"
},
"kind": "required",
"path": "passwordConfirm"
},
"password": {
"name": "ValidatorError",
"message": "Please provide a password for your profile",
"properties": {
"message": "Please provide a password for your profile",
"type": "required",
"path": "password"
},
"kind": "required",
"path": "password"
},
"email": {
"name": "ValidatorError",
"message": "Please use a valid e-mail",
"properties": {
"message": "Please use a valid e-mail",
"type": "required",
"path": "email"
},
"kind": "required",
"path": "email"
},
"name": {
"name": "ValidatorError",
"message": "Please use a name",
"properties": {
"message": "Please use a name",
"type": "required",
"path": "name"
},
"kind": "required",
"path": "name"
}
},
"_message": "User validation failed",
"name": "ValidationError",
"message": "User validation failed: passwordConfirm: Please confirm your password, password: Please provide a password for your profile, email: Please use a valid e-mail, name: Please use a name"
}
}
Just use required: true in your schema
If the validation fail, an error will be throw in:
const newUser = await User.create(req.body);
so you need to catch it and return an appropriate message to the user here (no in the model validation)
getting the following error while sending a request from postman
I am trying to create a hotel but when I send my post request to the server I am getting this response saying 500 internal server error.I am not able to find any error in the code .Can anyone tell me what's the issue.
I am sending this request
localhost:8000/api/hotel
{
"errors": {
"cheapestPrice": {
"name": "ValidatorError",
"message": "Path `cheapestPrice` is required.",
"properties": {
"message": "Path `cheapestPrice` is required.",
"type": "required",
"path": "cheapestPrice"
},
"kind": "required",
"path": "cheapestPrice"
},
"desc": {
"name": "ValidatorError",
"message": "Path `desc` is required.",
"properties": {
"message": "Path `desc` is required.",
"type": "required",
"path": "desc"
},
"kind": "required",
"path": "desc"
},
"title": {
"name": "ValidatorError",
"message": "Path `title` is required.",
"properties": {
"message": "Path `title` is required.",
"type": "required",
"path": "title"
},
"kind": "required",
"path": "title"
},
"distance": {
"name": "ValidatorError",
"message": "Path `distance` is required.",
"properties": {
"message": "Path `distance` is required.",
"type": "required",
"path": "distance"
},
"kind": "required",
"path": "distance"
},
"address": {
"name": "ValidatorError",
"message": "Path `address` is required.",
"properties": {
"message": "Path `address` is required.",
"type": "required",
"path": "address"
},
"kind": "required",
"path": "address"
},
"city": {
"name": "ValidatorError",
"message": "Path `city` is required.",
"properties": {
"message": "Path `city` is required.",
"type": "required",
"path": "city"
},
"kind": "required",
"path": "city"
},
"type": {
"name": "ValidatorError",
"message": "Path `type` is required.",
"properties": {
"message": "Path `type` is required.",
"type": "required",
"path": "type"
},
"kind": "required",
"path": "type"
},
"name": {
"name": "ValidatorError",
"message": "Path `name` is required.",
"properties": {
"message": "Path `name` is required.",
"type": "required",
"path": "name"
},
"kind": "required",
"path": "name"
}
},
"_message": "Hotel validation failed",
"name": "ValidationError",
"message": "Hotel validation failed: cheapestPrice: Path `cheapestPrice` is required., desc: Path `desc` is required., title: Path `title` is required., distance: Path `distance` is required., address: Path `address` is required., city: Path `city` is required., type: Path `type` is required., name: Path `name` is required."
}
this is the model Hotel.js file
import mongoose from "mongoose";
const {Schema} = mongoose
const HotelSchema = new mongoose.Schema({
name:{
type:String,
required:true
},
type:{
type:String,
required:true
},
city:{
type:String,
required:true
},
address:{
type:String,
required:true
},
distance:{
type:String,
required:true
},
photos:{
type:[String],
},
title:{
type:String,
required:true
},
desc:{
type: String,
required:true
},
rating:{
type: Number,
min:0,
max:5
},
rooms:{
type:[String]
},
// for showing cheapest hotels
cheapestPrice:{
type:Number,
required:true
},
// for showing featured hotels
featured:{
type:Boolean,
deafult:false,
}
})
export default mongoose.model("Hotel",HotelSchema)
This is the route hotel.js
import express from "express"
import Hotel from "../models/Hotel.js";
const router = express.Router();
router.post("/", async (req,res)=>{
const newHotel = new Hotel(req.body);
try{
const savedHotel = await newHotel.save()
res.status(200).json(savedHotel)
}catch(err){
res.status(500).json(err)
}
})
export default router
This is the main index.js file
import express from "express"
import dotenv from "dotenv"
import mongoose from "mongoose"
import hotelRoute from './routes/hotels.js'
const app = express()
dotenv.config()
const connect = async () =>{
try{
await mongoose.connect(process.env.MONGO)
console.log("Connected to mongodb")
}catch(err){
throw err;
}
}
mongoose.connection.on("connected",()=>{
console.log("mongodb connected")
})
mongoose.connection.on("disconnected",()=>{
console.log("mongodb disconnected")
})
//Middleware
app.use(express.urlencoded({extended:true}))
app.use(express.json())
app.use("/api/hotel",hotelRoute)
app.listen(8000,() =>{
connect()
console.log("Connected to backend")
})
}
In the console I'm getting
Connected to backend
mongodb connected
Connected to mongodb
first you must check your req.body data.
you can validate your req.body with joi validator
and (or) express-joi-validation.
in mongoose you must generate a model from your schema:
const Kitten = mongoose.model('Kitten', kittySchema);
The post method URL = http://localhost:8800/api/hotels
try using http://
if its free_preview is true means, the video data must preview to all and when the free_preview is false means its not might expose the video data.
But in this scenario if free_preview is false then also the video data is expose.
i want to make this to preview the videos wheather the free_preview is true otherwise the videos doesn't expose.
how can i solve this?
-----------------API CODE--------------------
export const courses = async (req, res) => {
const all = await Course.find({ published: true})
.populate("instructor", "_id name")
.exec();
res.json(all)
};
import { json } from "express";
import mongoose from "mongoose";
const { ObjectId } = mongoose.Schema;
const lessonSchema = new mongoose.Schema(
{
title: {
type: String,
trim: true,
minlength: 3,
maxlength: 320,
required: true,
},
slug: {
type: String,
lowercase: true,
},
content: {
type: String,
minlength: 200,
},
video: {},
time:{
type: Number,
required: true,
trim: true,
min: 1,
max: 5
},
free_preview: {
type: Boolean,
default: false,
},
},
{ timestamps: true }
);
const courseSchema = new mongoose.Schema(
{
name: {
type: String,
trim: true,
minlength: 3,
maxlength: 320,
required: true,
},
slug: {
type: String,
lowercase: true,
},
description: {
type: {},
minlength: 200,
required: true,
},
price: {
type: Number,
default: 500,
},
image: {},
category: String,
published: {
type: Boolean,
default: false,
},
paid: {
type: Boolean,
default: true,
},
instructor: {
type: ObjectId,
ref: "User",
required: true,
},
Category:{
type : String,
trim: true,
min: 4,
max: 200
},
lessons: [lessonSchema],
},
{ timestamps: true }
);
export default mongoose.model("Course", courseSchema);
----------------------------api response ----------------------------------
[
{
"price": 400,
"published": true,
"paid": true,
"_id": "61d73468f0ef1c2df856d580",
"slug": "nmap-for-ethical-hacking",
"instructor": {
"_id": "61d73336f0ef1c2df856d57f",
"name": "lenin royal"
},
"name": "Nmap for ethical hacking",
"description": "sfdsfdf",
"lessons": [
{
"free_preview": false,
"_id": "61d73721da89b03378321bc3",
"title": "intro",
"content": "sdfdfdff",
"video": {
"Location": "https://berrys01.s3.ap-south-1.amazonaws.com/_k8b_Khyz9GgTZkomm7WS.mp4",
"Bucket": "berrys01",
"Key": "_k8b_Khyz9GgTZkomm7WS.mp4",
"ETag": "\"00bf0fea24f997ac205c16de2ca3f7fa-2\""
},
"slug": "intro",
"updatedAt": "2022-01-06T18:38:25.674Z",
"createdAt": "2022-01-06T18:38:25.674Z"
},
{
"free_preview": true,
"_id": "61d737b8da89b03378321bc4",
"title": "hgdsfhgsdf",
"content": "dfsdfdf",
"video": {
"Location": "https://berrys01.s3.ap-south-1.amazonaws.com/Nqc6YL5LG1r3kWZIPigc1.mp4",
"Bucket": "berrys01",
"Key": "Nqc6YL5LG1r3kWZIPigc1.mp4",
"ETag": "\"4fbfb64ae636171fa7a7020ecc3b6a9e-16\""
},
"slug": "hgdsfhgsdf",
"updatedAt": "2022-01-06T18:40:56.963Z",
"createdAt": "2022-01-06T18:40:56.963Z"
},
{
"free_preview": true,
"_id": "61d737cada89b03378321bc5",
"title": "hello",
"content": "dfgdfg",
"video": {
"Location": "https://berrys01.s3.ap-south-1.amazonaws.com/fv5jEXzphsJ9al9DMKAr3.mp4",
"Bucket": "berrys01",
"Key": "fv5jEXzphsJ9al9DMKAr3.mp4",
"ETag": "\"72e0076dec633d7f3630628e92ba1891-3\""
},
"slug": "hello",
"updatedAt": "2022-01-06T18:41:14.132Z",
"createdAt": "2022-01-06T18:41:14.132Z"
},
{
"free_preview": true,
"_id": "61d737d6da89b03378321bc6",
"title": "rgrg",
"content": "dgdf",
"video": {
"Location": "https://berrys01.s3.ap-south-1.amazonaws.com/gmYnDGSrspH4jgfhC8ybr.mp4",
"Bucket": "berrys01",
"Key": "gmYnDGSrspH4jgfhC8ybr.mp4",
"ETag": "\"72e0076dec633d7f3630628e92ba1891-3\""
},
"slug": "rgrg",
"updatedAt": "2022-01-06T18:41:26.610Z",
"createdAt": "2022-01-06T18:41:26.610Z"
},
{
"free_preview": true,
"_id": "61d737e2da89b03378321bc7",
"title": "rgdgry56t5",
"content": "5yr",
"video": {
"Location": "https://berrys01.s3.ap-south-1.amazonaws.com/hzRW7TJn9ichITOk-3A-w.mp4",
"Bucket": "berrys01",
"Key": "hzRW7TJn9ichITOk-3A-w.mp4",
"ETag": "\"72e0076dec633d7f3630628e92ba1891-3\""
},
"slug": "rgdgry56t5",
"updatedAt": "2022-01-06T18:41:38.985Z",
"createdAt": "2022-01-06T18:41:38.985Z"
}
],
From what I see, a solution would be to do something like this
const courses = await Course
.find({ published: true })
.populate({
path: 'lessons',
match: { free_preview: true },
select: 'name -_id'
})
.exec();
I'm using node, express, mongoose for my back-end. I created User schema as follows,
const mongoose = require('mongoose');
const addressSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
no: { type: String },
firstStreet: { type: String },
secondStreet: { type: String },
city: { type: String, required: true },
district: { type: String }
})
const contactDetailsSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
landNumber: { type: String },
mobileNumber: { type: String },
momNumber: { type: String },
dadNumber: { type: String },
gardianNumber: { type: String }
})
const userSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
email: {
type: String,
required: true,
unique:true,
lowercase: true,
match: /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/
},
password: { type: String, required: true },
role: { type: String, required: true },
fullName: { type: String, required: true },
batch: { type: Number, required: true },
subject: [{
type: String
}],
school: { type: String, required: true },
birthday: { type: String },
address: { type: mongoose.Schema.Types.ObjectId, ref:'User' },
contactDetails: { type: mongoose.Schema.Types.ObjectId, ref:'User' },
stream: { type: String },
});
module.exports = {
user: mongoose.model('User', userSchema),
address: mongoose.model('Address', addressSchema),
contactDetails: mongoose.model('ContactDetails', contactDetailsSchema)
};
and I created a GET route to retrieve data from all users. I store these data in three separate mongoDB collections with same _id. And I want to get those all User data.
my User GET route is like this,
const userModels = require('../models/user');
const User = userModels.user;
const Address = userModels.address;
const ContactDetails = userModels.contactDetails;
router.get('/', (req, res) =>{
User
.find()
.exec()
.then(docs => {
console.log(docs);
const responce1 = {
count: docs.length,
Users: docs.map(doc => {
return {
Message: 'User Details',
Id: doc._id,
Email: doc.email,
Role: doc.role,
Full_Name: doc.fullName,
Batch: doc.batch,
Subject: doc.subject,
School: doc.school,
Birthday: doc.birthday,
Stream: doc.stream,
request: {
type: 'get',
url: 'http://localhost:3000/user/' +doc._id
}
}
})
}
Address
.find()
.exec()
.then(docs => {
console.log(docs)
responce2 = {
count: docs.length,
Address: docs.map(doc => {
return {
Message: 'Address',
_id: doc._id,
Address: doc.city,
First_Street: doc.firstStreet,
Second_Street: doc.secondStreet,
city: doc.city,
District: doc.district,
}
})
}
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
ContactDetails
.find()
.exec()
.then(docs => {
console.log(docs)
responce3 = {
count: docs.length,
ContactDetails: docs.map(doc => {
return {
Message: 'Contact Details',
_id: doc._id,
Land_Number: doc.landNumber,
Mobile_Number: doc.mobileNumber,
Mom_Number: doc.momNumber,
Dad_Number: doc.dadNumber,
Gardian_Number: doc.gardianNumber,
}
})
}
res.status(200).json([responce1,responce2,responce3]);
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
});
I get data like this,
[
{
"count": 3,
"Users": [
{
"Message": "User Details",
"Id": "5b8e68fb9c898543b4970628",
"Email": "new2#gmail.com",
"Role": "student",
"Full_Name": "Dinusha",
"Batch": 16,
"Subject": [
"ICT"
],
"School": "School",
"Birthday": "1996/10/23",
"Stream": "English",
"request": {
"type": "get",
"url": "http://localhost:3000/user/5b8e68fb9c898543b4970628"
}
},
{
"Message": "User Details",
"Id": "5b8e68fd9c898543b4970629",
"Email": "new3#gmail.com",
"Role": "student",
"Full_Name": "Dinusha",
"Batch": 16,
"Subject": [
"ICT"
],
"School": "School",
"Birthday": "1996/10/23",
"Stream": "English",
"request": {
"type": "get",
"url": "http://localhost:3000/user/5b8e68fd9c898543b4970629"
}
},
{
"Message": "User Details",
"Id": "5b8f52e707c299266c0a6b97",
"Email": "new4#gmail.com",
"Role": "student",
"Full_Name": "Dinusha",
"Batch": 16,
"Subject": [
"ICT"
],
"School": "School",
"Birthday": "1996/10/23",
"Stream": "English",
"request": {
"type": "get",
"url": "http://localhost:3000/user/5b8f52e707c299266c0a6b97"
}
}
]
},
{
"count": 3,
"Address": [
{
"Message": "Address",
"_id": "5b8e68fb9c898543b4970628",
"Address": "city",
"city": "city",
"District": "rathnapura"
},
{
"Message": "Address",
"_id": "5b8e68fd9c898543b4970629",
"Address": "city",
"city": "city",
"District": "rathnapura"
},
{
"Message": "Address",
"_id": "5b8f52e707c299266c0a6b97",
"Address": "city",
"city": "city",
"District": "rathnapura"
}
]
},
{
"count": 3,
"ContactDetails": [
{
"Message": "Contact Details",
"_id": "5b8e68fb9c898543b4970628",
"Land_Number": "072846",
"Mobile_Number": "7368438",
"Mom_Number": "7364738",
"Dad_Number": "648364"
},
{
"Message": "Contact Details",
"_id": "5b8e68fd9c898543b4970629",
"Land_Number": "072846",
"Mobile_Number": "7368438",
"Mom_Number": "7364738",
"Dad_Number": "648364"
},
{
"Message": "Contact Details",
"_id": "5b8f52e707c299266c0a6b97",
"Land_Number": "072846",
"Mobile_Number": "7368438",
"Mom_Number": "7364738",
"Dad_Number": "648364"
}
]
}
]
but I need to get data of every User like in this form
[
"Users":
{
"Message": "User Details",
"Id": "5b8e68fb9c898543b4970628",
"Email": "new2#gmail.com",
"Role": "student",
"Full_Name": "Dinusha",
"Batch": 16,
"Subject": [
"ICT"
],
"School": "School",
"Birthday": "1996/10/23",
"Stream": "English",
"request": {
"type": "get",
"url": "http://localhost:3000/user/5b8e68fb9c898543b4970628"
}
},
"Address":
{
"Message": "Address",
"_id": "5b8e68fb9c898543b4970628",
"Address": "city",
"city": "city",
"District": "rathnapura"
},
"ContactDetails":
{
"Message": "Contact Details",
"_id": "5b8e68fb9c898543b4970628",
"Land_Number": "072846",
"Mobile_Number": "7368438",
"Mom_Number": "7364738",
"Dad_Number": "648364"
},
]
can I get those data like that.
how to get data from mongodb as that custom form.
Use aggregate method and $lookup
https://mongoosejs.com/docs/api.html#aggregate_Aggregate-lookup
I'm using mongoose populate to try an create one-to-many relationships within my schemas
var clientSchema = new mongoose.Schema({
name: { type: String, required: true },
title: { type: String, default: "N/S" },
birthDate: { type: Date },
ssn: { type: String, default: "N/S" },
spouse: { type: String, default: "N/S" },
notes: { type: String, default: "N/S" },
address: { type: String, default: "N/S" },
city: { type: String, default: "N/S" },
state: { type: String, default: "N/S" },
zip: { type: String, default: "N/S" },
homePhone: { type: String, default: "N/S" },
workPhone: { type: String, default: "N/S" },
mobilePhone: { type: String, default: "N/S" },
fax: { type: String, default: "N/S" },
email: { type: String, default: "N/S" }
});
var caseSchema = mongoose.Schema({
_client: { type: mongoose.Schema.Types.ObjectId, ref: 'Client' },
name: { type: String, required: true },
lead: { type: String },
priority: { type: String },
dateOpened: { type: Date },
dateAccident: { type: Date },
status: { type: String },
sol: { type: Date },
description: { type: String }
});
What I want to be able to do is query the data base to get all cases with a given _client id.
I have this working but not the way I want it. As of right now, when I use the populate method
from within my route, I'm getting all of the cases with that client id, but I'm also getting
all of the clients, even though all of the clients are the exact same. It seem like this is a waste of resources to return the same client for each case. Is there any way to just return the client once, and then all of the related cases with it?
app.get('/cases/:id', function( req, res ) {
Case
.find( { _client: req.params.id } )
.populate('_client')
.exec( function( err, cases ) {
res.send( cases );
});
});
Here's what I'm getting back:
[
{
"_client": {
"name": "John Doe",
"birthDate": null,
"_id": "51705a7ed0ecd0a906000001",
"__v": 0,
"email": "",
"fax": "",
"mobilePhone": "",
"workPhone": "",
"homePhone": "",
"zip": "",
"state": "",
"city": "",
"address": "",
"notes": "",
"spouse": "",
"ssn": "",
"title": "Mr"
},
"name": "test",
"lead": "",
"priority": "",
"dateOpened": null,
"dateAccident": null,
"status": "",
"sol": null,
"description": "",
"_id": "5170679df8ee8dd615000001",
"__v": 0
},
{
"_client": {
"name": "John Doe",
"birthDate": null,
"_id": "51705a7ed0ecd0a906000001",
"__v": 0,
"email": "",
"fax": "",
"mobilePhone": "",
"workPhone": "",
"homePhone": "",
"zip": "",
"state": "",
"city": "",
"address": "",
"notes": "",
"spouse": "",
"ssn": "",
"title": "Mr"
},
"name": "newest case",
"lead": "",
"priority": "",
"dateOpened": null,
"dateAccident": null,
"status": "",
"sol": null,
"description": "",
"_id": "517067d8806f060b16000001",
"__v": 0
},
{
"_client": {
"name": "John Doe",
"birthDate": null,
"_id": "51705a7ed0ecd0a906000001",
"__v": 0,
"email": "",
"fax": "",
"mobilePhone": "",
"workPhone": "",
"homePhone": "",
"zip": "",
"state": "",
"city": "",
"address": "",
"notes": "",
"spouse": "",
"ssn": "",
"title": "Mr"
},
"name": "adding new case",
"lead": "Me",
"priority": "Urgent",
"dateOpened": null,
"dateAccident": null,
"status": "",
"sol": null,
"description": "",
"_id": "51709a16806f060b16000002",
"__v": 0
}
]
This just doesn't seem right to send all of this bloat to my view to be rendered. Should I even be using populate for one-to-many like this?
All of the examples that I see on mongoose.com are one-to-one, with the exception of embedded documents.
If you don't want the client repeated for each case, you'd be better off separately querying for the client and then combining that result with the result of your Case query (without the populate) in whatever way you need.
BTW, '/cases/:id' is a pretty confusing URL for getting cases by client id and not case id.