Create index on multikey and nested document using mongoose - indexing

I'm creating index using mongoose it will check uniqueness of Name, PName and OName (Name+PName+OName should be unique). Please check below implementation
var MySchema = new mongoose.Schema({
Name: { type: String, required: true},
Details: [{
PName: { type: String, required: true},
OName: { type: String, required: true}
}]
});
MySchema.index({Name: 1, Details.PName: 1, Details.OName:1 }, {unique: true});
Document
{"Name" : "Testing123","Details" : [{"PName" : "Page1", "OName" : "Ob1"},
{"PName" : "Page1", "OName" : "Ob1"}]}
I need to restrict above document for insertion as the Name, PName and OName is not unique.

Related

Mongoose population issue at express.js

Hello evryone i have issue last 2 days tryin to populate reviews on company list.
Im trying to get list of all companys with their reviews.
Every review is assigned to company Id.
On postman response i get empty array : []
Here is the code im having isuses with;
Company Model:
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var slug = require("mongoose-slug-generator");
mongoose.plugin(slug);
var CompanySchema = new Schema({
title: {type: String, required: true},
slug: { type: String, slug: "title" },
address: {type: String, required: true},
totalRating: {type: Number, required: false},
description: {type: String, required: false},
facebookLink: {type: String, required: false},
twitterLink: {type: String, required: false},
googleLink: {type: String, required: false},
linkedIn:{type: String, required: false},
instagramLink:{type: String, required: false},
contactNumber:{type: Number, required: false},
website:{type: String, required: false},
email:{type: String, required: false},
review: [{type: Schema.Types.ObjectId, ref: "Review"}],
user: { type: Schema.ObjectId, ref: "User", required: true },
}, {timestamps: true});
module.exports = mongoose.model("Company", CompanySchema);
Review Model :
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var ReviewSchema = new Schema({
title: {type: String, required: true},
description: {type: String, required: true},
rating: {type: String, required: true},
user: { type: Schema.ObjectId, ref: "User", required: true },
company: {type: Schema.ObjectId, ref:"Company"}
}, {timestamps: true});
module.exports = mongoose.model("Review", ReviewSchema);
And where i populate it :
exports.companyList = [
function (req, res) {
try {
Company.
find({id: req._id}).
populate("review").
then((companies)=>{
if(companies.length > 0){
return apiResponse.successResponseWithData(res, "Uspješno 1", companies);
}else{
return apiResponse.successResponseWithData(res, "Uspješno 2", []);
}
});
} catch (err) {
//Baci error 500...
return apiResponse.ErrorResponse(res, err);
}
}
];
Ive tryed evrything thanks infront.
Try changing in your Company Model
review: [{type: Schema.Types.ObjectId, ref: "Review"}]
to
review: {type: Schema.Types.ObjectId, ref: "Review"}
Then when you try to populate, I assume you either pass the _id of the company in your params or body of the request, so most likely:
req.params.id
or
req.body.id
the actual function:
module.exports = {
fncName: (req, res) => {
Company.findById(req.params.id)
.populate({
path: 'review',
})
.exec((err, company) => {
if (!err) {
if(companies.length > 0){
return apiResponse.successResponseWithData(res, "Uspješno 1", companies);
}else{
return apiResponse.successResponseWithData(res, "Uspješno 2", []);
}
}else {
console.log(err)
}
})
}
}
I am not sure how you register the router but it could look something like this:
const router = require ('express-promise-router')();
router.get('/get-company', nameOfTheController.fncName);
Note: to populate review from Company Model you do not necessarily need this line in your Review Model:
company: {type: Schema.ObjectId, ref:"Company"}

Fulltext mongodb $text search query in graphql-compose-mongoose

I'm unable to figure out how to construct a graphql query for performing the mongodb fulltext search using the text index. https://docs.mongodb.com/manual/text-search/
I've already created a text index on my string in the mongoose schema but I don't see anything in the schemas that show up in the grapqhl playground.
A bit late, though I was able to implement it like so
const FacilitySchema: Schema = new Schema(
{
name: { type: String, required: true, maxlength: 50, text: true },
short_description: { type: String, required: true, maxlength: 150, text: true },
description: { type: String, maxlength: 1000 },
location: { type: LocationSchema, required: true },
},
{
timestamps: true,
}
);
FacilitySchema.index(
{
name: 'text',
short_description: 'text',
'category.name': 'text',
'location.address': 'text',
'location.city': 'text',
'location.state': 'text',
'location.country': 'text',
},
{
name: 'FacilitiesTextIndex',
default_language: 'english',
weights: {
name: 10,
short_description: 5,
// rest fields get weight equals to 1
},
}
);
After creating your ObjectTypeComposer for the model, add this
const paginationResolver = FacilityTC.getResolver('pagination').addFilterArg({
name: 'search',
type: 'String',
query: (query, value, resolveParams) => {
resolveParams.args.sort = {
score: { $meta: 'textScore' },
};
query.$text = { $search: value, $language: 'en' };
resolveParams.projection.score = { $meta: 'textScore' };
},
});
FacilityTC.setResolver('pagination', paginationResolver);
Then you can assign like so
const schemaComposer = new SchemaComposer();
schemaComposer.Query.addFields({
// ...
facilities: Facility.getResolver('pagination')
// ...
});
On your client side, perform the query like so
{
facilities(filter: { search: "akure" }) {
count
items {
name
}
}
}

MyOrder in Express.js

How to create order model and ordersRoute in express.js ?
var globalConfig = require('../../public/js/globalConfig'),
_ = require('underscore'),
mongoosePaginate = require('mongoose-paginate');
module.exports = function(mongoose) {
var Schema = mongoose.Schema,
deepPopulate = require('mongoose-deep-populate')(mongoose);
var OrderSchema = new Schema({
code : String,
date : { type: Date, default: Date.now },
status : { type: String, enum: _.keys(globalConfig.orderStatus)},
_products : [{
//product : {type: Schema.Types.ObjectId, ref: 'Product'},
product : {},
quantity : Number
}],
user : {type: Schema.Types.ObjectId, ref: 'User'},
totalOrder : Number,
_addresses : {
billing : {
name : String,
address : String,
zipCode : String,
city : String,
country : String
},
// Times
createdAt : { type: Date, default: Date.now },
updatedAt : { type: Date, default: Date.now }
});
OrderSchema.plugin(mongoosePaginate);
OrderSchema.plugin(deepPopulate, {});
module.exports = mongoose.model('Order', OrderSchema);
}

Not create multiple table in Realm.

I'm creating tables of Realm database using React native. My function of creating table is,
const Realm = require('realm');
exports.createTables = function(tableName, pkey, structure) {
let realm = new Realm({
schema: [{name: tableName, primaryKey: pkey, properties: structure}]
});
return realm;
};
and i calling this method,
import realmDatabase from './RealmDatabase';
realmDatabase.createTables("MstUnitType", "UnitTypeId", {
"UnitTypeName" : "string",
"UnitTypeId" : "string",
} );
realmDatabase.createTables("MstTime", "TimeId", {
"TimeId" : "string",
"From" : "string",
"To" : "string",
} );
realmDatabase.createTables("MstQuestions", "QuestionId", {
"QuestionId" : "string",
"Question" : "string",
} );
I got only MstUnitType table in defualt.realm file other 2 table not created while i run above 3 create table methods one by one.
Yes i found solution of above. Following way we can create multiple tables at a time,
var Realm = require('realm');
const CarSchema = {
name: 'Car',
properties: {
make: 'string',
model: 'string',
miles: {type: 'int', default: 0},
}
};
const PersonSchema = {
name: 'Person',
properties: {
name: 'string',
birthday: 'date',
cars: {type: 'list', objectType: 'Car'},
picture: {type: 'data', optional: true}, // optional property
}
};
// Initialize a Realm with Car and Person models
let realm = new Realm({schema: [CarSchema, PersonSchema]});

keystoneJS relationship to self

I want to create a Category model that can hold another category, but having a problem with reference field that I can set my current category to it self
Any suggestions how to achieve hierarchical categories?
Does KeystoneJS have filter like 'not equal'?
In other hand, maybe I can set default reference field to it self and it will be like a root...
My current code below:
var keystone = require('keystone'),
Types = keystone.Field.Types;
var PageCategory = keystone.List('PageCategory', {
map: { name: 'name' },
autokey : { from: 'name', path: 'key'}
});
PageCategory.add({
name: { type: String, required: true, unique: true},
image: { type: Types.CloudinaryImage, label: "Category Image"},
description : { type: Types.Html, wysiwyg: true},
parent: { type: Types.Relationship, ref: "PageCategory", label: "Parent category"}
});
PageCategory.relationship({ ref: "PageCategory", path: "parent"});
PageCategory.register();
I think you have misunderstood how Model.relationship() works.
It has three options:
path, this is the "virtual" field name that will hold the values
ref, this is the model that we reference
refPath, this is the field in the referenced model that we populate path with
I think something in line with this will work for you
PageCategory.relationship({ ref: "PageCategory", path: "children", refPath: "parent"});