I want to match a string with employee ID, employee Name , project name
My Models : (employee)
const employeeSchema = new mongoose.Schema(
{
employeeID: { type: String, unique: true, required: true },
departmentID: { type: mongoose.Types.ObjectId, ref: 'Department', default: null },
employeeName: { type: String, required: true },
gender: { type: String, default: "", enum: ["Male", "Female"] },
designation: { type: String, default: "" },
email: { type: String, default: null },
branchName: { type: String, default: "" },
employeeType: { type: String, default: "" },
jobStatus: { type: String, default: "" },
joiningDate: { type: Date, default: "" },
leavingDate: { type: Date, default: "" },
comments: { type: String, default: "" },
managerID: { type: mongoose.Types.ObjectId, ref: 'Employee', default: null },
region: { type: String, default: "" },
}
);
(project)
const projectSchema = new mongoose.Schema(
{
projectName: {type: String, required: true},
tech: {type: String, required: true},
startDate: {type: Date, required:true},
endDate: {type: Date, required:true},
customerID:{type:mongoose.Types.ObjectId, ref:'Customer'}
}
);
(employee-Project)
const employeeProjectSchema = new mongoose.Schema(
{
empID: {type: mongoose.Types.ObjectId, required: true, ref: 'Employee'},
projectID: {type: mongoose.Types.ObjectId, required: true, ref: 'Project'},
allocation: {type: [Number]},
assignStartDate: {type: Date},
assignEndDate: {type: Date},
}
);
I'm running my query from employee-project table which is my main table.
What I wanna do is to match a string with with employeeID and employeeName(employee table) and also with projectName(project table).
What I'm doing right now (which is wrong)
async rpSearch(data): Promise<any> {
try {
const result = await MongooseEmployeeProject.find()
.populate({
path: 'empID',
select: 'employeeID employeeName designation region comments resourceManager',
match:{
type:{data}
}
})
.populate({
path: 'projectID',
select: 'projectName tech startDate endDate customerID'
match:{
type:{data}
})
please guide me
First, path must be the field name of the schema. you set path with "employeeID" but "empID" is correct as employeeProjectSchema's field name.
Second, you set match but there is no type field in your employeeSchema and employeeProjectSchema neither. so you have to remove match.
async rpSearch(data): Promise<any> {
try {
const result = await MongooseEmployeeProject.find()
.populate({
path: 'empID',
select: 'employeeID employeeName designation region comments resourceManager'
})
.populate({
path: 'projectID',
select: 'projectName tech startDate endDate customerID'
})
Related
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?
schema:
var UserSchema = new Schema({
id: { type: String, unique: true },
username: { type: String, unique: true },
password: String,
first_name: String,
last_name: String,
email: { type: String, unique: true },
phone: { type: String, unique: true },
status: { type: Boolean, default: false },
role: {
type: String,
enum: ["REGULAR", "ADMIN", "SUPER-ADMIN", "OPERATOR"],
default: "REGULAR",
},
tenantRef: { type: Schema.Types.String, ref: "tenant" },
teamRef: { type: Schema.Types.String, ref: "team" },
customerRef: { type: Schema.Types.String, ref: "customer" },
created: { type: Date, default: Date.now },
});
var CustomerSchema = new Schema({
id: { type: String, unique: true },
name: String,
plan: String,
billing: String,
status: { type: Boolean, default: true },
created: { type: Date, default: Date.now },
});
controller:
userController.getUsers = async function (req, res) {
const users = await UserSchema.find({}).populate({
path: "teamRef",
});
console.log(users);
return res.status(200).send(users);
};
Here i am trying to join user and customer so that i can get customer name along with user data .
I am using above way but it is not working.
Please take a look how can i do it
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"});
I have a collection of user which has id, firstName, lastName. id field of user collection has been used in another collection.
Is there any way to find all collection which used user id?
user schema:
let userSchema = new mongoose.Schema({
firstName: {
type: String,
trim: true,
required: true
},
lastName: {
type: String,
trim: true,
required: true
}
},
{
timestamps: true,
usePushEach: true
});
training schema:
var trainingSchema = new mongoose.Schema({
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
name: {type: String, required: true},
institution: {
instituteName: {type: String, required: true},
type: {type: String, required: true},
address: {
country: String,
state: String,
city: String
}
},
startDate: Date,
endDate: Date,
achievements: String,
createdAt: Date,
updatedAt: Date,
endorsers: [{
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
},
profilePic: {
container: {type: String,default: null},
name: { type: String, default: null }
},
currentPosition: {type: String,default: ""},
currentWorkingCompany: {type: String,default: ""}
}],
});
In above schema userId come from user collection
Note: similar to this which is available in MYSQL:
SELECT
ke.referenced_table_name 'parent table',
ke.referenced_column_name 'parent column',
ke.table_name 'child table',
ke.column_name 'child column',
ke.constraint_name
FROM
information_schema.KEY_COLUMN_USAGE ke
WHERE
ke.referenced_table_name IS NOT NULL
AND table_schema = 'your_db_name'
ORDER BY ke.referenced_table_name;
Source: here
You probably need MySQL function named join. In MongoDB it is named $lookup and it is part of aggregate function.
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;