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);
}
Related
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"}
Getting error unknown top level operator $regex
search.vue `
let questDocuments = await conversation
.find({ query: { $limit: 100, $search: q, skippop: true } })
.then(response => {`
q is the string being passed
service hook
before: {
all: [],
find: [
hookBeforeFind,
search({
fields: ["label"],
deep: true
})
],
Model
const conversation = new Schema(
{
label: { type: String, required: true },
nodeId: { type: String, required: true },
details: { type: String },
url: { type: String },
creator: { type: String },
handle: { type: String },
date: { type: String },
From search bar add expression to search. E.g "the"
Add $regex to the whitelist option of the Mongoose service:
app.use('/messages', service({
Model,
whitelist: [ '$regex' ]
}));
try this
// regex to find records that start with letter any name , example "e"
Model.aggregate([
{
$match: {
field_name: {
$regex: "^" + searchName,
$options: "i"
}
}
}]).exec(function(err, result) {
if (err) { // handle here }
if (result) { // do something }
}
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.
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]});
I've trying to get the sencha touch 2 data management examples to work but with no use. Here is the code of a simple model and store that are not working (getCount returns 0).
Ext.define('MyClient.model.Product', {
extend:'Ext.data.Model',
config:{
fields:['name', 'image'],
proxy:{
type:'ajax',
url:'http://localhost/st2/Projets/my-client-sencha/data/products.json',
reader:{
type:'json',
rootProperty:'products',
successProperty:'success'
}
}
}
});
Ext.define('MyClient.store.ProductsStore', {
extend:'Ext.data.Store',
config:{
model:'MyClient.model.Product',
autoLoad:true,
autoSync:true
}
});
In the launch function I have these lines:
var prod = Ext.create('MyClient.store.ProductsStore');
prod.load();
alert(prod.getCount());
And finally here's my products.json:
[
{
"name":"test"
}
]
I'm not getting any errors in the console but still the getCount always returns 0. Can use some help here please.
EDIT: wrong JSON, not working with this neither:
{
"success":true,
"products": [
{
"name":"test"
}
]
}
Because of your setting rootProperty:'products', your json has to be like
{
products: [
{
"name":"test"
}
]
}
if you do not want to change server response remover rootProperty from config.
have a look at Json Reader doc
Ahh... you forgot about asyn nature of the load()....
var prod = Ext.create('MyClient.store.ProductsStore');
prod.load(function ( ){
alert(prod.getCount());
});
Notice that it prod.load() is using only for testing purposes, as far you have set property autoLoad: true.
In your snippet the loader would make 2 similar calls.
Cheers, Oleg
Ext.define('MyBizilinkms.model.Customer', {
extend: 'Ext.data.Model',
config: {
identifier:'uuid',
fields: [
'CustId',
'EMail',
'Title',
'FName',
'MdInitial',
'LName',
'PhnNum',
'SecondPhnNo',
'DOB',
'Address',
'SecondAddress',
'City',
'State',
'Zip',
'Country',
'RecieveEmail',
'IsSaveonServer',
{
name: 'Full_Name',
type:'string',
convert:function(v, rec) {
return rec.data.FName + " " + rec.data.LName;
}
}],
validations: [
{
type: 'format',
name: 'EMail',
matcher: /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/,
message:"Valid Email Required"
},
{
name: 'PhnNum',
type : 'custom',
message : "Valid Phone required",
validator : function(config, value, model) {
var reg = /^[0-9]{3}-[0-9]{3}-[0-9]{4}$/;
return reg.test(value);
}
},
{
name: 'SecondPhnNum',
type : 'custom',
message : "Valid 2nd Phone required",
validator : function(config, value, model) {
if (!Ext.isEmpty(value)) {
var reg = /^[0-9]{3}-[0-9]{3}-[0-9]{4}$/;
return reg.test(value)
}
return true;
}
},
{
type: 'presence',
name: 'FName',
message : "First Name is required"
},
{
type: 'presence',
name: 'LName',
message : "Last Name is required"
},
{
type: 'presence',
name: 'Address',
message : "Address is required"
},
{
type: 'presence',
name: 'City',
message : "City is required"
},
{
name: 'State',
type : 'custom',
message : "Valid State required",
validator : function(config, value, model) {
var reg = /^(AK|AL|AR|AZ|CA|CO|CT|DC|DE|FL|GA|HI|IA|ID|IL|IN|KS|KY|LA|MA|MD|ME|MI|MN|MO|MS|MT|NB|NC|ND|NH|NJ|NM|NV|NY|OH|OK|OR|PA|RI|SC|SD|TN|TX|UT|VA|VT|WA|WI|WV|WY)$/i;
if(Ext.isEmpty(value))
value = '00'
var state = value.replace(/^\s+|\s+$/g, "");
return reg.test(state)
}
},
{
name: 'Zip',
type : 'custom',
message : "Valid Zip required",
validator : function(config, value, model) {
var reg = /(^\d{5}$)|(^\d{5}-\d{4}$)/;
return reg.test(value)
}
},
{
type: 'presence',
name: 'Country',
message : "Country is required"
}
]
},
getFullName: function() {
return this.get('FName') + '' + this.get( 'LName');
}
});