Getting item in an array with matching id mongoose - javascript

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: []}
})

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.

How to store empty array in mongodb

I want to store empty array in user schema's friends key. But, mongoose won't let me to add empty array of friends.
Here's my User schema
const userSchema = mongoose.Schema({
firstName: {
type: String,
required: true,
},
lastName: {
type: String,
required: true,
},
userName: {
type: String,
unique: true,
required: true,
},
email: {
type: String,
required: true,
unique: true,
validate: [validator.isEmail, "Please enter a valid Email"],
},
password: {
type: String,
required: true,
minlength: [6, "Password must be at least 6 characters"],
},
friends: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
unique: true,
},
],
});
And here's my code to pull data from array and save empty array
const index = req.user.friends.findIndex(friend => friend.toString() === req.params.id);
if(index !== -1){
req.user.friends.splice(index, 1);
}else{
req.user.friends.push(req.params.id);
}
const user = new User(req.user);
await user.save({validateBeforeSave: false});
return res.json({success: true});
specify default value instead
friends: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
unique: true,
default: []
},
],

Node Populate Array with object reference

I need to Populate courses of StudentSchema with the courses (Object_id) from CoursesSchema that belong to the major same as students major
let StudentSchema = new Schema({
_id: new Schema.Types.ObjectId,
emplId: {
type: Number,
required: true
},
major:{
type: String,
required: true
},
courses:[{
type: mongoose.Schema.Types.ObjectId,
ref: 'courses',
grade:{
type: String,
required: false,
}
}],
});
const courseSchema = new mongoose.Schema({
code: {
type: String,
required: true
},
title: {
type: String,
required: true
},
//array of majors that a courses is required for e.g: ['CS', 'CIS']
major: {
type: Array,
required: false,
},
//
CIS:{
type: Boolean,
required: false,
},
CNT:{
type: Boolean,
required: false,
},
CS:{
type: Boolean,
required: false,
},
GIS:{
type: Boolean,
required: false,
},
})
What do I do?
StudentCoursesRouter.get('/studentcourses', (req, res) => {
Courses.find({CS: true}, (err, courses) => {
if ( err ) {
console.log('Error occured while getting records');
res.json(err);
} else {
courseMap = {}
courses.forEach(function(course) {
courseMap[course._id] = course._id;
});
//res.send(courses);
Students.find({empleId: 12345678}).courses.push(courses);
}
res.json(Students);
})
This is what i am doing but it is not populating courses of student and gives an empty array for courses.
API Request Response Screenshot
You mention populate but you are not using populate?
e.g. Students.find({empleId: 12345678}).populate('course')
If you want it lean u also need to install mongoose-lean-virtuals
e.g. Students.find({empleId: 12345678}).populate('course').lean({ virtuals: true })

Need help regarding POST API

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,

I am getting E11000 duplicate key error collection: restauracja.tables index: reservations.user.email_1 dup key: { : null }

This is my Table Collection:
const tableSchema = new Schema({
number: {
type: Number,
required: true,
unique: true
},
seats: {
type: Number,
required: true
},
reservations: [orderSchema]
})
const Table = mongoose.model('Table', tableSchema)
And OrderSchema:
const orderSchema = new Schema({
time: {
type: String,
required: true
},
date: {
type: String
},
user: userSchema
})
And User Collection and Schema:
const userSchema = new Schema({
firstname: {
type: String,
required: true
},
lastname: {
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true
},
phone: {
type: String
},
password: {
type: String,
required: true
},
admin: {
type: Boolean,
default: false,
required: true
}
})
const User = mongoose.model('User', userSchema)
When i would like to create the second (i have no idea why first is adding) instance of table, i am getting error like in title:
MongoError: E11000 duplicate key error collection: restauracja.tables index: reservations.user.email_1 dup key: { : null }
I can create only one document in table, but i have different values in the second one.

Categories

Resources