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

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?

Related

Mongodb mongoose join two collection and fetch data

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

Populate a property of a mongoose schema with all the data in another collection

I have a model with articles, and would like to populate an array of data with all the documents in a collection.
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ArticlesSchema = new mongoose.Schema({
path: {
type: String,
required: true,
unique: true,
},
base_headline: {
type: String,
required: true,
},
intro: {
type: String,
required: true,
},
featured_image: {
type: String,
required: true,
},
author: {
type: String,
required: true,
},
platform_filter: {
type: String,
},
free_filter: {
type: String,
},
content_type: {
type: String,
required: true,
},
data: [{ type: Schema.Types.ObjectId, ref: 'DesignProducts' }],
date: {
type: Date,
default: Date.now,
},
});
module.exports = mongoose.model('Articles', ArticlesSchema);
The data property should be populated with all documents in the DesignProducts collection.
I tried running this but the data array is still empty:
Article.findOne({ path: slug }).populate('data').exec();
Here is what the designProducts model looks like:
const mongoose = require('mongoose');
const DesignProductsSchema = new mongoose.Schema({
name: {
type: String,
required: true,
unique: true,
},
intro: {
type: String,
required: true,
},
website: {
type: String,
required: true,
},
date: {
type: Date,
default: Date.now,
},
});
module.exports = mongoose.model('DesignProducts', DesignProductsSchema);
This array should be populated with all the documents in the DesignProducts collection:

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

how to use find in populate (mongoose)

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

How to store range(in geocircle radius form) in mongoose schema

I am building an e-commerce application. Every store has a delivery range so i want to set delivery range of every store in the database to show the store only to those who falls in the delivery range.
Store Schema.
const mongoose = require("mongoose");
const sellerSchema = new mongoose.Schema({
name:{
type: String,
required: true,
},
type: {
type: String,
required: true
},
location: {
type: {
type: "String",
enum:['Point']
},
coordinates: {
type: [Number],
index: '2dsphere'
}
},
owner: {
type: String,
required: true
},
items: [{
type: mongoose.Schema.Types.ObjectId,
ref: "items"
}],
contact: {
type: String,
required: true
},
loginId: {
index:true,
unique: true,
type: String,
},
password: {
type: String,
required: true
},
createdAt: {
type: Date,
default: Date.now
}
});
const sellerModel = mongoose.model("sellers",sellerSchema);
module.exports = sellerModel;