2dsphere index on nested document not working - mongodb

I wanted to save multiple locations in the below schema and run geolocation queries.
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
/**
* Offer Schema
*/
var LocSchema = new Schema({
'type': {
type: String,
required: true,
enum: ['Point', 'LineString', 'Polygon'],
default: 'Point'
},
coordinates: [Number]
});
var LocationSchema = new Schema({
address:{type:String},
loc:[LocSchema]
});
var OfferSchema = new Schema({
name: {
type: String,
default: '',
required: 'Please fill Offer name',
trim: true
},
description:
{
type:String,
default:'',
required:'Please fill offer description',
trim: true
},
shortDesc:
{
type:String,
default:'',
trim: true
},
image:
{
type:String,
default:'',
required:'Please upload image'
},
locations:[LocationSchema],
created: {
type: Date,
default: Date.now
},
startDate: {
type: Date,
default: Date.now
},
endDate: {
type: Date,
default: Date.now
},
user: {
type: Schema.ObjectId,
ref: 'User'
},
category:
{
type: Schema.ObjectId,
ref :'Category'
}
});
OfferSchema.index({'locations.loc': '2dsphere'});
mongoose.model('Offer', OfferSchema);
When I run save on the object I get "something went wrong" error, however I am able to save the document if I delete the index.
Can someone tell me if I am doing something wrong.

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

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 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;

Mongoose populate nested not working

I have this user model:
const userSchema = new mongoose.Schema({
...,
instances: {
type: Array,
default: [{
role: 'user'
}],
role: {
type: String,
enum: ['admin', 'user']
},
company: {
type: mongoose.Schema.ObjectId,
ref: 'Company'
},
},
},
{
timestamps: true
}
);
And company model:
const companySchema = new mongoose.Schema({
name: {
type: String,
required: true
},
logo: {
type: mongoose.Schema.ObjectId,
ref: 'File',
required: true
}
}, { timestamps: true });
And this pre find method:
userSchema.pre('findOne', function () {
this.populate({
path: 'instances.company',
populate: {
path: 'logo',
model: 'File'
}
});
});
I want to populate the instances companies on each find, and populate the logo of the company.
The thing is, that the company is populated, but not the logo path.
What am I doing wrong?

Population to sub-scheme in Mongoose

I have two schemas:
Clinic:
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var ProcedureSchema = mongoose.Schema({
name: {
type: String,
trim: true,
required: true
},
alias: {
type: String,
trim: true,
required: true
}
});
var ClinicSchema = mongoose.Schema({
name: {
type: String,
trim: true,
required: true
},
procedures: [ProcedureSchema]
});
module.exports = mongoose.model('Clinic', ClinicSchema);
and Record:
var mongoose = require('mongoose'),
Patient = require('./patient'),
User = require('./user'),
Clinic = require('./clinic'),
Schema = mongoose.Schema;
var RecordSchema = Schema({
doctor: {
type: Schema.Types.ObjectId,
ref: 'User'
},
clinic: {
type: Schema.Types.ObjectId
},
date: {
type: Date
},
patient: {
type: Schema.Types.ObjectId,
ref: 'Patient'
},
procedure: {
type: [Schema.Types.ObjectId],
ref: 'Clinic'
}
});
module.exports = mongoose.model('Record', RecordSchema);
In record schema i store all ids of procedure, which sub-scheme for Clinic
I want to get full object of procedures in record.
I try this query:
Record.find({}).
populate('procedures.procedure').
populate('doctor').
populate('patient').
exec(function(err, records) {
...
});
But get only array of ids, instead array of objects.
Where is problem?
You totally mix all schemes:
populate('procedures.procedure')
But you have not procedures in RecordSchema. Even if it is type mistake, an you mean procedure.procedures - you don't have procedures in ProcedureSchema.
read more about references in MongoDB especially http://docs.mongodb.org/manual/applications/data-models-tree-structures/
Try to make nesting path less than 2. Something like this:
var User,
Procedure,
Clinic,
Patient,
Record;
function defineModels(mongoose, fn) {
var Schema = mongoose.Schema,
ObjectId = Schema.ObjectId;
User = new Schema({
...
});
Procedure = new Schema({
name: { type: String, trim: true, required: true },
alias: { type: String, trim: true, required: true }
});
Clinic = new Schema({
name: { type: String, trim: true, required: true },
procedures: [ProcedureSchema]
});
Patient = new Schema({
...
});
Record = new Schema({
'date': {type: Date, default: Date.now},
'doctor': {type: ObjectId, ref: 'User'},
'clinic': {type: ObjectId, ref: 'Clinic'},
'patient': {type: ObjectId, ref: 'Patient'},
'procedure': {type: ObjectId, ref: 'Procedure'},
});
mongoose.model('User', User);
mongoose.model('Procedure', Procedure);
mongoose.model('Clinic', Clinic);
mongoose.model('Patient', Patient);
mongoose.model('Record', Record);
fn();
}
exports.defineModels = defineModels;
Hope this help.