Doubts on Mongodb query - mongodb

I was designing a classifieds web app with the MERN stack. The MongoSchema is as shown below
const UserSchema = new Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true
},
books: [{
title: { type: String },
author: { type: String },
desc: { type: String },
price: { type: String },
image: { data: Buffer, contentType: String }
}],
date: {
type: Date,
default: Date.now
}
});
So all the other info except the books[] will be available after the initial sign-up, but what I want to do is to update the books array every time the user wishes to post a book for selling.
I'm planning to find the user by id, but I'm not quite sure how to add/append the info to the books array.

There are some answers to your question already in Stackoverflow.
For example:
Using Mongoose / MongoDB $addToSet functionality on array of objects
You can do something like this:
UserModel.js
const mongoose = require("mongoose");
const UserSchema = new Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true
},
books: [{
title: { type: String },
author: { type: String },
desc: { type: String },
price: { type: String },
image: { data: Buffer, contentType: String }
}],
date: {
type: Date,
default: Date.now
}
});
module.exports = User = mongoose.model("user", userSchema);
After that, in your router file you can try something like this for the books array:
const res = await User.updateOne({ email: 'gintama#bandainamco.com' }, {'$addToSet':{
'books':{
title: "Gintama: The Final",
author: "Sorachi",
desc: "Final Arc",
price: "44.99",
image: "src"
}}); //addToSet if you don't want any duplicates in your array.
OR
const res = await User.updateOne({ email: 'gintama#bandainamco.com' }, {'$push':{
'books':{
title: "Gintama: The Final",
author: "Sorachi",
desc: "Final Arc",
price: "44.99",
image: "src"
}}); //push if duplicates are okay in your array

Related

Re: Correct MongoDb Relationships

Hi clever MongoDB people,
I am extremely new to Mongo DB and am trying to teach myself coding but I am battling with the practical side of collections.
I am attempting to create an employee management system and would like to know how do I get the different schemas/collections to only deal with the individual User’s employees.
A user will register using this schema;
const mongoose = require("mongoose");
const UserSchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
lowercase: true,
},
companyName: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
role: {
type: String,
default: "customer",
},
CreatedAt: {
type: Date,
default: () => Date.now(),
},
UpdatedAt: {
type: Date,
default: () => Date.now(),
},
});
const User = mongoose.model("User", UserSchema:
);
module.exports = User;
Then the system takes them to a Profile page where they create a profile;
Profile Schema:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const ProfileSchema = new Schema({
userId: {
type: Schema.Types.ObjectId,
required: true,
},
contactPerson: {
type: String,
required: true,
},
companyName: {
type: String,
required: true,
},
mobileNo: {
type: String,
required: true,
},
workNo: {
type: String,
},
email: {
type: String,
required: true,
},
industry: {
type: String,
},
CreatedAt: {
type: Date,
default: () => Date.now(),
},
UpdatedAt: {
type: Date,
default: () => Date.now(),
},
});
const Profile = mongoose.model("Profile", ProfileSchema);
module.exports = Profile;
Then they can add their employees.
Employee Schema:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const EmployeeSchema = new Schema({
userId: {
type: Schema.Types.ObjectId,
required: true,
},
employeeNo: {
type: String,
},
title: {
type: String,
},
employeeName: {
type: String,
required: true,
},
surname: {
type: String,
required: true,
},
gender: {
type: String,
},
race: {
type: String,
},
passportNo: {
type: String,
},
IDnumber: {
type: Number,
},
DOB: {
type: Date,
},
aka: {
type: String,
},
midName: {
type: String,
},
marriage: {
type: String,
},
passportExpires: {
type: Date,
},
mobileNo: {
type: String,
},
empEmail: {
type: String,
lowercase: true,
},
CreatedAt: {
type: Date,
default: () => Date.now(),
},
UpdatedAt: {
type: Date,
default: () => Date.now(),
},
});
const Employee = mongoose.model("Employee", EmployeeSchema);
module.exports = Employee;
Once an employee has been created there are various schemas connected with the employee, such as Personal contact details schema, Job details schema, Emergency contact details schema and so on.
This is my Emergency contact details schema:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const EmergencySchema = new Schema({
userId: {
type: Schema.Types.ObjectId,
required: true,
},
emergContactPerson: {
type: String,
required: true,
},
emergWorkNo: {
type: String,
},
emergMobileNo1: {
type: String,
required: true,
},
emergMobileNo2: {
type: String,
},
medicAidName: {
type: String,
},
medicPlan: {
type: String,
},
medicMemberNo: {
type: String,
},
medicDepCode: {
type: Number,
},
CreatedAt: {
type: Date,
default: () => Date.now(),
},
UpdatedAt: {
type: Date,
default: () => Date.now(),
},
});
const Emergency = mongoose.model("Emergency", EmergencySchema);
module.exports = Emergency;
My question is How do I create a one-to-many relationship between my schemas so that each User will only see their employees and their personal details?
Please can you help me?

How to get SQL's "AND" operator behavior in mongoose

const ItemSchema = new mongoose.Schema({
categoryId: {
type: mongoose.Types.ObjectId,
required: true,
ref: 'Category'
},
companyId: {
type: mongoose.Types.ObjectId,
required: true,
ref: 'Company'
},
name: {
type: String,
required: true
}
})
const CategorySchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
displayOrder: {
type: Number,
required: true,
},
description: {
type: String
}
});
const companySchema = new mongoose.Schema(
{
name: {
type: String,
required: true,
},
email: {
type: String,
required: true
},
address: {
address: String,
city: String,
state: String,
country: {
type: mongoose.Schema.Types.ObjectId,
ref: 'countrycodes'
},
pincode: String,
}
});
I have this above schema and trying to get the items which has company name="KFC" and category name="food"
Along with the items I want to populate the company and category objects.
const itemList = await Item.find().populate(
{
path: 'companyId',
match: { name: 'KFC'},
select: '_id name'
}).populate(
{
path: 'categoryId',
match: { name: 'food'},
select: '_id name'
}
).lean();
I tried using populate as shown below but this returns items which do not have category name="food" but has comp
name="KFC"
How can I get the items which has company name="KFC" and category name="food" and ignore the ones which do not satisfy both company and category condition.
Also, Is populate() the right way to get the results I want?

Return objects with ids matching the ids in another array mongoose

I'm having an issue running a query on my mongo DB. I want to return the objects that match the ids in the array of Ids. Not sure what I'm doing wrong everywhere online suggests doing it this exact way.
Mongoose Query
MovieSchema.statics.findKnownForMovies = function(ids) { return this.find({ id: { $in: [ids]}});
}
Mongoose Schema
const MovieSchema = new Schema({
adult: { type: Boolean },
category: {type: String},
id: { type: Number, required: true, unique: true },
poster_path: { type: String },
overview: { type: String },
release_date: { type: String },
original_title: { type: String },
genre_ids: [{ type: Number }],
original_language: { type: String },
title: { type: String },
backdrop_path: { type: String },
popularity: { type: Number },
vote_count: { type: Number },
video: { type: Boolean },
vote_average: { type: Number })
Array of ids
[ '577922', '487558', '429203' ]

how create a schema for create a place on mongoDB use moongose

I'm need to create a schema to add restaurts and then show this places on a map on react. like
1-name place
2-author
3-lat
4-log
5-description
6- open hour
this is need to id user connect for now how create and show on the react app and react native app.
you can following this code
const mongoose = require("mongoose");
const { Schema } = mongoose;
const restaurtSchema = new Schema({
title: { type: String, required: true, trim : true },
description: { type: String, required: true },
image: { type: String },
address: { type: String, required: true },
location: {
lat: { type: Number, required: true },
lng: { type: Number, required: true },
},
creator: { type: mongoose.Types.ObjectId, required: true, ref: 'User'},
date: { type: Date, default: Date.now },
});
module.exports = mongoose.model("restaurt", restaurtSchema );
You can 2dsphere index for save location of restaurant and it helps you find nearest restaurant or calculate distance.
const mongoose = require("mongoose");
const { Schema } = mongoose;
const restaurtSchema = new Schema({
title: { type: String, required: true, trim : true },
description: { type: String, required: true },
image: { type: String },
address: { type: String, required: true },
locationLongLat: {
'type': {type: String, enum: "Point", default: "Point"},
coordinates: {type: [Number], default: [0, 0]}
}
creator: { type: mongoose.Types.ObjectId, required: true, ref: 'User'},
date: { type: Date, default: Date.now },
});
restaurtSchema.index({'locationLongLat.coordinates': "2dsphere"});

Mongoose Schema, how to nest objects in one schema?

In my mongoose schema, I have defined some data types and two object array.
The first object dish which should be ok.
But in the second nested object order I want to include the first object dish into and I do not know the way to do this properly.
module.exports = function( mongoose) {
var ShopSchema = new mongoose.Schema({
shopName: { type: String, unique: true },
address: { type: String},
location:{type:[Number],index: '2d'},
shopPicUrl: {type: String},
shopPicTrueUrl:{type: String},
mark: { type: String},
open:{type:Boolean},
shopType:{type:String},
dish: {type: [{
dishName: { type: String},
tags: { type: Array},
price: { type: Number},
intro: { type: String},
dishPic:{ type: String},
index:{type:Number},
comment:{type:[{
date:{type: Date,default: Date.now},
userId:{type: String},
content:{type: String}
}]}
}]},
order:{type:[{
orderId:{type: String},
date:{type: Date,default: Date.now},
dish:{type: [dish]},//!!!!!!!!! could I do this?
userId:{type: String}
}]}
});
this is correct way to design model
var mongoose = require('mongoose');
Schema = mongoose.Schema;
var DishSchema = new mongoose.Schema({
dishName: { type: String },
tags: { type: Array },
price: { type: Number },
intro: { type: String },
dishPic: { type: String },
index: { type: Number },
comment: { type: [{
date: {type: Date, default: Date.now },
userId: {type: String },
content: {type: String }
}]}
});
var ShopSchema = new mongoose.Schema({
shopName: { type: String, unique: true },
address: { type: String },
location: { type: [Number], index: '2d' },
shopPicUrl: { type: String },
shopPicTrueUrl: { type: String },
mark: { type: String },
open: { type: Boolean },
shopType: { type: String },
dish: { type: [DishSchema] },
order: { type: [{
orderId: { type: String },
date: { type: Date, default: Date.now },
dish: { type: [DishSchema] },
userId: { type: String }
}]}
});
var Shop = mongoose.model('Shop', ShopSchema);
module.exports = Shop;