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