Need help regarding POST API - javascript

I have a mongoose schema as below, I am trying to create a new club buts always getting undefined error. I checked many times but not success. Can someone please help me to CRUD operation. I am new to programming, trying my best.
const schoolSchema = new mongoose.Schema
({
schoolName: { type: String, unique: true, required: true },
feePlan: {
primary: { type: String, enum: ['Plan-A', 'Plan-B'], default: 'Plan-A', required: true },
secondary: { type: String, enum: ['Plan-A', 'Plan-B'], default: '', },
},
schoolContact: {
email:
{ type: String, lowercase: true, trim: true, index: true, unique: true, required: true },
phonePrimary:
{ type: String, trim: true, unique: true, required: true },
phoneSecondary:
{ type: String, trim: true },
headInstructor:
{ type: String, required: true },
websiteUrl: { type: String, trim: true, default: '' },
businessAddress:
{
street: { type: String, required: true },
city: { type: String, required: true },
state: { type: String, required: true },
zip: { type: String, required: true },
country: { type: String, required: true },
},
otherAddress: {
street: { type: String, required: true },
city: { type: String, required: true },
state: { type: String, required: true },
zip: { type: String, required: true },
country: { type: String, required: true },
},
},
active: { type: Boolean, default: true },
timestamps: { type: Date, deafault: true },
});
const schoolModel = mongoose.model('School', schoolSchema);
module.exports = schoolModel;
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
router.post('/add', function (req, res, next) {
let schoolName = req.body.schoolName;
let feePlan = req.body.feePlan;
let primary = req.body.primary;
let secondary = req.body.secondary;
let schoolContact = req.body.schoolContact;
let email = req.body.email;
let phonePrimary = req.body.phonePrimary;
let phoneSecondary = req.body.phoneSecondary;
let headInstructor = req.body.headInstructor;
let websiteUrl = req.body.websiteUrl;
let businessAddress = req.body.businessAddress;
let street = req.body.street;
let city = req.body.city;
let state = req.body.state;
let zip = req.body.zip;
let country = req.body.country;
let otherAddress = req.body.otherAddress;
let streetOth = req.body.streetOth;
let cityOth = req.body.cityOth;
let stateOth = req.body.stateOth;
let zipOth = req.body.zipOth;
let countryOth = req.body.countryOth;
let schoolObj = new schoolModel({
schoolName: schoolName,
feePlan: {
primary: primary,
secondary: secondary,
},
schoolContact: {
email: email,
phonePrimary: phonePrimary,
phoneSecondary: phoneSecondary,
headInstructor: headInstructor,
websiteUrl: websiteUrl,
businessAddress:
{
street: street,
city: city,
state: state,
zip: zip,
country: country,
},
otherAddress: {
streetOth: streetOth,
cityOth: cityOth,
stateOth: stateOth,
zipOth: zipOth,
countryOth: countryOth,
},
},
active: { type: Boolean, default: true },
timestamps: { type: Date, deafault: true },
});
schoolObj.save(function (err, schoolObj) {
if (err) {
res.send({ status: 500, message: 'Unable to Add school' });
console.log(schoolObj);
}
else {
res.send({ status: 200, message: 'school Added Successfully', schoolDetails: schoolObj });
}
});
});

Thanks Justinas, and everyone who took a look. I was able to solve the issue. I don't need to declare all the fields. Just below solution worked.
let schoolName = req.body.schoolName;
let feePlan = req.body.feePlan;
let schoolContact = req.body.schoolContact;
let schoolObj = new schoolModel({
schoolName: schoolName,
feePlan: feePlan,
schoolContact: schoolContact,

Related

Mongoose populate() is returning an empty array

I am trying to use mongoose populate function but in response I am getting empty array. I know there are several questions talking about the same subject but none worked for my case.
My objective is to populate my Order document.
This is how my schemas are organized:
Menu.js
const mongoose = require("mongoose");
const { Schema } = mongoose;
const Food = require("./Food");
const Drink = require("./Drink");
const MenuSchema = new Schema({
code: {
type: mongoose.ObjectId,
required: true,
unique: true,
},
name: {
type: String,
required: true,
},
food: {
type: [Food.schema],
required: false,
},
drinks: {
type: [Drink.schema],
required: false,
},
type: {
type: String,
},
createdAt: {
type: Date,
default: Date.now,
},
});
module.exports = mongoose.model("Menu", MenuSchema);
Note: Im using Food.schema and Drink.schema inside my Arrays instead of making a ref. Im storing the Food and Drink models inside of the Menu model
Food.js
const mongoose = require("mongoose");
const { Schema } = mongoose;
const FoodSchema = new Schema({
code: {
type: mongoose.ObjectId,
required: true,
unique: true,
},
description: {
type: String,
required: true,
},
ingredients: {
type: [],
required: false,
default: [],
},
stock: {
type: Number,
required: true,
},
type: {
type: String,
enum: ["starter", "main", "dessert"],
required: true,
},
price: {
type: Number,
required: true,
},
createdAt: {
type: Date,
default: Date.now,
},
});
module.exports = mongoose.model("Food", FoodSchema);
Drink.js
const mongoose = require("mongoose");
const { Schema } = mongoose;
const DrinkSchema = new Schema({
code: {
type: mongoose.ObjectId,
required: true,
unique: true,
},
description: {
type: String,
required: true,
},
stock: {
type: Number,
required: true,
},
price: {
type: Number,
required: true,
},
createdAt: {
type: Date,
default: Date.now,
},
});
module.exports = mongoose.model("Drink", DrinkSchema);
Order.js
const mongoose = require("mongoose");
const { Schema } = mongoose;
const OrderSchema = new Schema({
code: {
type: mongoose.ObjectId,
required: true,
unique: true,
},
type: {
type: String,
required: true,
enum: ["restaurant", "takeaway", "delivery"],
},
food: {
type: [{ type: mongoose.ObjectId, ref: "Food" }],
required: false,
default: [],
},
drinks: {
type: [{ type: mongoose.ObjectId, ref: "Drink" }],
required: false,
default: [],
},
orderValue: Number,
client_id: {
type: mongoose.ObjectId,
ref: "Client",
required: false,
},
createdAt: {
type: Date,
default: Date.now,
},
});
module.exports = mongoose.model("Order", OrderSchema);
This is the controller where I'm trying to make my populate work. Whenever I remove the populate method I get the _id references for the Food and Drink arrays.
TableController.js
exports.getOrderFromTable = async (req, res) => {
const { code, tableCode } = req.params;
try {
const foundRestaurant = await Restaurant.findOne({ code: code });
const foundTable = foundRestaurant.tables.filter(
(table) => table.code == tableCode
);
console.log(foundTable[0].order_id);
const foundOrder = await Order.findOne({
_id: foundTable[0].order_id,
})
.populate("food")
.populate("drinks");
res.send(foundOrder);
} catch (err) {
res.json({ message: err });
}
};
And this is what the mongoose debugger returns when I run the controller:
Mongoose: restaurants.findOne({ code: new ObjectId("62a60dcb9fe25d276815675c") }, { projection: {} })
new ObjectId("62a60ece9fe25d27681567b7")
Mongoose: orders.findOne({ _id: new ObjectId("62a60ece9fe25d27681567b7") }, { projection: {} })
Mongoose: foods.find({ _id: { '$in': [ new ObjectId("62a60e039fe25d276815677d"), new ObjectId("62a60e169fe25d2768156785") ], [Symbol(mongoose#trustedSymbol)]: true }}, { skip: undefined, limit: undefined, perDocumentLimit: undefined, projection: {}})
Mongoose: drinks.find({ _id: { '$in': [ new ObjectId("62a60e259fe25d276815678d"), new ObjectId("62a60e3c9fe25d276815679c") ], [Symbol(mongoose#trustedSymbol)]: true }}, { skip: undefined, limit: undefined, perDocumentLimit: undefined, projection: {}})
And finally this is the JSON file I get when I do a GET http request using Postman:
{
"_id": "62a60ece9fe25d27681567b7",
"code": "62a60ece9fe25d27681567b6",
"type": "restaurant",
"food": [],
"drinks": [],
"orderValue": 25,
"createdAt": "2022-06-12T16:05:34.513Z",
"__v": 0
}
Thank you for any help. I've been really struggling with this method.

MissingSchemaError: Schema hasn't been registered for model UserAddress.address

Been pulling my hair out for hours now, just can't figure out why the field refuses to populate.
What I want to do is return the AddressId field populated with values instead of just an ID, but nothing I've tried works, none of the solutions I found do anything.
If you need any other code from the project, I will update the question.
Any help is highly appreciated.
Order Model:
const mongoose = require("mongoose");
const orderSchema = new mongoose.Schema(
{
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
required: true,
},
addressId: {
type: mongoose.Schema.Types.ObjectId,
ref: "UserAddress.address",
required: true,
},
totalAmount: {
type: Number,
required: true,
},
items: [
{
productId: {
type: mongoose.Schema.Types.ObjectId,
ref: "Product",
},
payablePrice: {
type: Number,
required: true,
},
purchasedQty: {
type: Number,
required: true,
},
},
],
paymentStatus: {
type: String,
enum: ["Pending", "Completed", "Cancelled", "Refund"],
required: true,
},
paymentType: {
type: String,
enum: ["CoD", "Card", "Wire"],
required: true,
},
orderStatus: [
{
type: {
type: String,
enum: ["Ordered", "Packed", "Shipped", "Delivered"],
default: "Ordered",
},
date: {
type: Date,
},
isCompleted: {
type: Boolean,
default: false,
},
},
],
},
{ timestamps: true }
);
module.exports = mongoose.model("Order", orderSchema);
Address Model:
const mongoose = require("mongoose");
const addressSchema = new mongoose.Schema({
name: {
type: String,
required: true,
trim: true,
min: 10,
max: 60,
},
mobileNumber: {
type: String,
required: true,
trim: true,
},
pinCode: {
type: String,
required: true,
trim: true,
},
locality: {
type: String,
required: true,
trim: true,
min: 10,
max: 100,
},
address: {
type: String,
required: true,
trim: true,
min: 10,
max: 100,
},
cityDistrictTown: {
type: String,
required: true,
trim: true,
},
state: {
type: String,
required: true,
required: true,
},
landmark: {
type: String,
min: 10,
max: 100,
},
alternatePhone: {
type: String,
},
addressType: {
type: String,
required: true,
enum: ["home", "work"],
required: true,
},
});
const userAddressSchema = new mongoose.Schema(
{
user: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: "User",
},
address: [addressSchema],
},
{ timestamps: true }
);
mongoose.model("Address", addressSchema);
module.exports = mongoose.model("UserAddress", userAddressSchema);
Code that runs the query:
const Order = require("../models/order");
const Cart = require("../models/cart");
const Address = require("../models/address");
const Product = require("../models/product");
exports.getOrders = (req, res) => {
Order.find({ user: req.user._id })
.select("_id paymentStatus paymentType orderStatus items addressId")
.populate("items.productId", "_id name productImages")
.populate("addressId")
.exec((error, orders) => {
if (error) {console.log(error)
return res.status(400).json({ error });}
if (orders) {
res.status(200).json({ orders });
}
});
};

.findOne / .findById keep running if no result is found

I face an issue that i can't resolve alone.
I have a MongoDB collection, in this collection i have 1 document atm.
When i use .findById(_id) or .findOne({_id : id}) with the right _id, everything works.
When i use .findById(_id) or .findOne({_id : id}) with the wrong _id (for test purposes), i have no response (no undefined, no null, nothing) from the DB and my request keep running.
Ty for your time, take care !
EDIT :
Document :
export interface OrderDocument extends mongoose.Document {
user: UserDocument['_id'];
asset_bought: AssetDocument['_id'];
asset_b_symbol: string;
asset_sold: AssetDocument['_id'];
asset_s_symbol: string;
exchange: ExchangeDocument['_id'];
exchange_name: string;
is_draft: Boolean;
amount: number;
atm_price: number;
date: Date;
}
Collection's schema :
const orderSchema = new mongoose.Schema(
{
_id: { type: mongoose.Schema.Types.ObjectId },
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'users',
required: true,
},
asset_bought: {
type: mongoose.Schema.Types.ObjectId,
ref: 'assets',
required: true,
},
asset_b_symbol: {
type: String,
required: true,
},
asset_sold: {
type: mongoose.Schema.Types.ObjectId,
ref: 'assets',
required: true,
},
asset_s_symbol: {
type: String,
required: true,
},
exchange: {
type: mongoose.Schema.Types.ObjectId,
ref: 'exchanges',
required: true,
},
exchange_name: {
type: String,
required: true,
},
is_draft: { type: Boolean, default: false },
amount: { type: Number, required: true },
atm_price: { type: Number, required: true },
date: { type: Date, required: true },
},
{ timestamps: true }
);
Service
export async function findAndPopulateOrders(
searchType: 'id' | 'one' | 'many',
query: FilterQuery<OrderDocument>,
_collections: Array<string>
) {
const collections = _collections.join(' ');
if (searchType === 'id') {
return await OrderModel.findById(query).populate(collections);
} else if (searchType === 'one') {
return await OrderModel.findOne(query).populate(collections);
} else if (searchType === 'many') {
return await OrderModel.find(query).populate(collections);
} else {
return {};
}
}

Getting item in an array with matching id mongoose

I have a db with some objects that have embedded array of cards.
I want to get a card with matching id from a user that matches the Id that I am looking for. so far I am only able to return the wrong card.
async getCard(id: string, cardId: string) {
if (!id) throw new CardNotFoundError(id);
let query = {'user.id': id, 'cards.id': cardId};
const card = (await this.byQuery(query)).cards[0];
if (card) return card;
throw new CardNotFoundError("" || id);
}
my schema
const CardUserSchema = new Schema(
{
id: {
...trimmedString,
required: true,
index: true,
unique: true
},
phoneNumber: { ...trimmedString, required: true, unique: true },
email: { ...trimmedString, required: false },
}
const CardSchema = new Schema({
id: {
...trimmedString,
required: true,
index: true,
unique: true
},
})
const CardMainSchema = SchemaFactory(
{
id: {
...trimmedString,
required: true,
index: true,
unique: true
}
user: { type: CardUserSchema, required: true },
cards: {type: [CardSchema], default: []}
})

Mongoose model schema referencing not working - Ecommerce model

I am creating multi vendor ecommerce platform, with the following schema.
var user = new Schema(
{
uid: { type: String, index: true, unique: true },
firstName: { type: String, required: true, default: null },
lastName: { type: String, default: null, default: null },
userEmail: { type: String, unique: true, required: true, lowercase: true, },
userProfileImg: { type: String, required: true, default: null },
userDesignation: { type: String, default: null },
userMobile: { type: Number, required: true, default: null },
products: { type: Schema.Types.ObjectId, ref: 'Product' },
}
);
var product = new Schema(
{
sku: { type: String, required: true, unique: true },
title: { type: String, required: true },
category: { type: Array, default: [] },
images: { type: Array, default: [], },
groups: { type: Array, default: [], },
price: { type: Number, default: null, },
unit: { type: String, default: null, },
quantity: { type: Number, default: null, },
description: { type: String, default: null, },
},
);
var AllUser = mongoose.model('User', user, 'AllUsers');
var Allproducts = mongoose.model('Product', product, 'AllProducts');
how can i save multiple products while referring to multiple users? Later i want to populate products based on the users.
Your problem is in referencing the collection. In here when you compile your models
var AllUser = mongoose.model('User', user, 'AllUsers');
var Allproducts = mongoose.model('Product', product, 'AllProducts');
you use Product and for database collection you use AllProducts. That's the problem so...try doing it like this
var Users = mongoose.model('Users', user, 'Users');
var Products = mongoose.model('Products', product, 'Products');
Give it a proper naming convention.
Also there is s typo here in this code.. here I have fixed it
var product = new Schema(
{
sku: { type: String, required: true, unique: true },
title: { type: String, required: true },
category: { type: Array, default: [] },
images: { type: Array, default: [] },
groups: { type: Array, default: [] },
price: { type: Number, default: null },
unit: { type: String, default: null },
quantity: { type: Number, default: null },
description: { type: String, default: null}
}
);
also in your user schema
var user = new Schema(
{
uid: { type: String, index: true, unique: true },
firstName: { type: String, required: true, default: null },
lastName: { type: String, default: null, default: null },
userEmail: { type: String, unique: true, required: true, lowercase: true,
},
userProfileImg: { type: String, required: true, default: null },
userDesignation: { type: String, default: null },
userMobile: { type: Number, required: true, default: null },
products: [{ type: Schema.Types.ObjectId, ref: 'Product' }]
}
);
make products as an array type so that you can store multiple product ids

Categories

Resources