How to store empty array in mongodb - javascript

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

Related

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

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 })

How to sustainably organise user schema in mongoose

I have a user which should have the following fields and currently has following schema:
const UserSchema = new Schema(
{
email: {
type: String,
required: true,
index: { unique: true },
lowercase: true,
},
isVerified: { type: Boolean, default: false }, // whether user has confirmed his email
name: { type: String, required: false },
password: { type: String, required: true, minLength: 6 }, // object with next two included?
passwordResetExpires: Date,
passwordResetToken: String,
roles: [{ type: 'String' }], // Array of strings?
username: { type: String, required: false },
token: [{ type: String, required: false }], // used to send verification token via email
},
{ timestamps: true },
);
So yes, what is the world's default standard for organising user schemas. This schema's fields are pretty common, right?

Updating count of individual sub document that's in an array of a mongo document

So the example right now is for the User table.. I have a UserWeapon document embedded that is an array of all the weapon's a user has and how many kills they have with the weapon. I want to write a query that when given the userId, weaponId, and new kills, it'll update the sub document accordingly.
So something like
const user = await User.findById(userId);
const userWeapon = await user.userWeapon.findById(weaponId);
userWeapon.kills = userWeapon.kills + newAmmountOfKills
user.save();
What would be the most efficient way to do this?
Schemas:
const UserWeaponSchema = new Schema({
weapon: { type: Schema.Types.ObjectId, ref: 'Weapon' },
user: { type: Schema.Types.ObjectId, ref: 'User' },
kills: {
type: Number,
required: true,
unique: false,
},
deaths: {
type: Number,
required: true,
unique: false
},
equippedSkin: {
type: Schema.Types.ObjectId, ref: 'WeaponSkin',
required: false,
},
ownedWeaponSkins: [{ type: Schema.Types.ObjectId, ref: 'WeaponSkin'}]
});
const UserSchema = new Schema({
username: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
},
weapons: [{
type: Schema.Types.ObjectId, ref: 'UserWeapon'
}],
});
You can use $inc operator and run update operation, something like:
UserWeaponSchema.update({ weapon: weaponId, user: userId }, { '$inc': { 'kills': newAmmountOfKills } })

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