I have a model for employee information im using in a MEAN stack and want to reference the store name they will work at in a stores model, would the following be correct?
Employees:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var muv = require('mongoose-unique-validator');
var schema = new Schema({
firstName: {type: String, required: true},
lastName: {type: String, required: true},
empId: {type: String, required: true, unique: true},
num: {type: String, required: true},
job: {type: String, required: true},
store: {type: Schema.Types.storeName, ref: 'Stores'},
});
schema.plugin(muv);
module.exports = mongoose.model('Message', schema);
Stores:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var schema = new Schema({
storeName: {type: String, required: true},
lat: {type: String, required: true},
long: {type: String, required: true},
});
module.exports = mongoose.model('Stores', schema);
You're close! You want to reference the ID of the store, not the name. When Mongoose does the 'Join', it will see the ObjectID store in the store profile field and match it to an ObjectID in the Stores collection.
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var muv = require('mongoose-unique-validator');
var schema = new Schema({
firstName: {type: String, required: true},
lastName: {type: String, required: true},
empId: {type: String, required: true, unique: true},
num: {type: String, required: true},
job: {type: String, required: true},
store: {type: type: Schema.ObjectId, ref: 'Stores'}, //Reference store ObjectId.
});
schema.plugin(muv);
module.exports = mongoose.model('Message', schema);
Related
i have two schemas: Item and Category. I want to use Category in Items, how can i merge them? Here is the code:
Category:
const mongoose = require('mongoose');
const categorySchema = mongoose.Schema({
name: {type: String, required: true},
description: {type: String, required: true},
city: {type: String, required: true},
});
var categoryData = mongoose.model("categoryData", categorySchema);
module.exports = categoryData;
Item:
const mongoose = require('mongoose');
const categSchema = require("./category.js")
const itemSchema = mongoose.Schema({
name: {type: String, required: true},
created: {type: Date, required: true, unique: true},
category: [categSchema],
quantity: {type: Number, required: true}
});
var itemData = mongoose.model("itemData", itemSchema);
module.exports = itemData;
And the error that i get is "TypeError: Invalid schema configuration: model is not a valid type within the array category."
What am I doing wrong?
Instead of module.exports = categoryData
Do the following:
module.exports = categorySchema.
I have the following query working with mongo, it returns the expected result
db.getCollection('trainings').find({"sections.employees.employee":ObjectId("5d3afa1a58a7160ea451d1db")})
but when I try the following call with mongoose, it returns an empty array
Training.find({'section.employees.employee': "5d3afa1a58a7160ea451d1db"})
Need some helping to translate the mongo query to mongoose.
If you need anything else just add a comment and I will post here.
It's worth mentioning that I have already tried passing a new ObjectId with the String value, but it also returns an empty array.
Edit: Query usage
return await Training.find({'section.employees.employee': "5d3afa1a58a7160ea451d1db"})
Edit: Model
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const EmployeeSection = new Schema({
employee: {type: Schema.Types.ObjectId, ref: 'Employee', required: true},
fulfilled: {type: Boolean, default: null},
});
const Section = new Schema({
order: {type: Number, required: true},
date: {type: Date},
employees: {type: [EmployeeSection]},
answers: {type: Number},
hits: {type: Number}
});
const GoalSchema = new Schema({
understanding: {type: Number, required: true},
fixation: {type: Number, required: true}
});
const Evidence = new Schema({
description: {type: String, required: true},
file: {type: String}
});
const Question = new Schema({
participants: {type: Number},
answers: {type: Number},
hits: {type: Number}
});
const TrainingSchema = new Schema({
company: {type: Schema.Types.ObjectId, ref: 'Company', required: true, index: true},
creationDate: { type: Date, default: Date.now },
title: {type: String},
obs: {type: String},
questionNumber: {type: Number},
reference: {type: String},
sections: {type: [Section]},
goals: {
answers: {type: GoalSchema, required: true},
hits: {type: GoalSchema, required: true}
},
evidences: {type: [Evidence]},
questions: {type: [Question]},
area: {type: Schema.Types.ObjectId, ref: 'TrainingArea', required: true},
});
const Training = mongoose.model('Training', TrainingSchema);
module.exports = Training;
I am willing to change the Model schema, if the problem really lays there, but didn't really want to do it.
Why its always a typo?
db.getCollection('trainings').find({"sections.employees.employee":ObjectId("5d3afa1a58a7160ea451d1db")})
Training.find({'section.employees.employee': "5d3afa1a58a7160ea451d1db"})
Forgot s on sections
Made the problem a bit easier for me.
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/training", { useNewUrlParser: true })
const util = require("util")
const Schema = mongoose.Schema;
const EmployeeSection = new Schema({
employee: {type: Schema.Types.ObjectId, ref: 'Employee', required: true}
});
const Section = new Schema({
employees: {type: [EmployeeSection]}
});
const TrainingSchema = new Schema({
sections: {type: [Section]}
});
const Training = mongoose.model('Training', TrainingSchema);
Training.find(
{
"sections.employees.employee": mongoose.Types.ObjectId("5d3afa1a58a7160ea451d1db")
})
.exec()
.then(result => {
console.log(util.inspect(result, false, null, true /* enable colors */))
}).catch(err =>{
console.log(err)
})
I have a little issue getting lookup to work. It returns an empty array. I use contactId field in Billing Collection. And I use the contact _id created when entry in Contact Collection in mongodb (Can see it in Robomongo). I have few Billings with ContactId corresponding to the _id of few Contacts. Is my syntaxe correct ? Do I miss something ? Thank you for your help.
Below is my lookup syntaxe
Contact.aggregate([
{
$lookup: {
from: "Billing",
localField: "_id",
foreignField: "contactId",
as: "BillingMembership"
}
}
]).exec(function (err, contacts) {
if (err) {
return res.status(500).json({
title: 'An error occurred',
error: err
});
}
res.status(200).json({
message: 'Success',
obj: contacts
});
});
Below is the result I get back from the database.
(4) [Object, Object, Object, Object]
0:Object
BillingMembership:Array(0)
length:0
__proto__:Array(0)
additionalInterests:"MFM/REI"
billingEmail:"john#netdr.net"
cellPhone:6787025500
dateBirth:"1555-02-02T00:00:00.000Z"
firstName:"qtazerqr'efsg"
gogsMbrType:"Resident Applicant"
gogsYearJoined:"20111"
homePhone:6787025500
lastName:"gzaetrsg"
memberSuffix:", DO"
middleName:"fzerqgrre"
notes:"htrfjghdnt"
officeEmail:"john#netdr.net"
officePhone:6787025500
personalEmail:"john#netdr.net"
practiceId:"592e4c1638a494089c50c8c8"
praticeType:"MFM/High Risk"
spFirstNm:"gsertdhy"
spLastNm:"rthytrfgj"
spSuffix:"syhtdrh"
website:"trshdty"
__v:0
_id:"5932db29eb4dfe0de4a8a36d"
__proto__:Object
1:Object
2:Object
3:Object
Mongoose Schema Contact
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var mongooseUniqueValidator = require('mongoose-unique-validator');
var schema = new Schema({
firstName: {type: String, required: true},
middleName: {type: String, required: true},
lastName: {type: String, required: true},
dateBirth: {type: Date, required: true},
memberSuffix: {type: String, required: true},
officePhone: {type: Number, required: true},
homePhone: {type: Number, required: true},
cellPhone: {type: Number, required: true},
officeEmail: {type: String, required: true},
billingEmail: {type: String, required: true},
personalEmail: {type: String, required: true},
gogsMbrType: {type: String, required: true},
gogsYearJoined: {type: String, required: true},
spFirstNm: {type: String, required: true},
spLastNm: {type: String, required: true},
spSuffix: {type: String, required: true},
notes: {type: String, required: true},
praticeType: {type: String, required: true},
additionalInterests: {type: String, required: true},
website: {type: String, required: true},
practiceId: {type: Schema.Types.ObjectId, ref: 'Practice'}
});
schema.plugin(mongooseUniqueValidator);
module.exports = mongoose.model('Contact', schema);
Mongoose Schema Billing
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var mongooseUniqueValidator = require('mongoose-unique-validator');
var schema = new Schema({
reason: {type: String, required: true},
amount: {type: Number, required: true},
membership: {type: String, required: true},
membershipYear: {type: Schema.Types.ObjectId, ref: 'Membership'},
type: {type: String, required: true},
date: {type: String, required: true},
contactId: {type: Schema.Types.ObjectId, ref: 'Contact'},
conferenceId: {type: Schema.Types.ObjectId, ref: 'Conference'}
});
schema.plugin(mongooseUniqueValidator);
module.exports = mongoose.model('Billing', schema);
Solved. thanks to Veeram.
I used Change your from: "Billing" to from: "billings"
Are these schemas valid?
var StudentSchema = new mongoose.Schema({
first_name: {type: String, required:true},
last_name: {type: String, required: true},
mother_name : {type: String, required: true},
siblings:[{
name:{type: String, required: true},
age:{type:Number, required: true},
school:{type:String, required:true}
}]
});
And this
var WinSchema = new mongoose.Schema({
event:{type: mongoose.Schema.Types.ObjectId, ref:'Event'},
winners : [{
student: {type: mongoose.Schema.Types.ObjectId, ref: 'Student'},
position: {type:String, enum:["First","Second","Third","Consolation"]}
}]
});
WinSchema.index({event:1,winners.student:1},{unique:true});
mongoose.model('Win',WinSchema);
Can we nest it as shown in StudentSchema?
Can we create a unique index on nested documents?
Yes you can nest it, see schema example here and of course you can create a index on nested documents here is the example.
Product Schema:
var ProductSchema = new Schema({
productName: {type: String, required: true},
});
Client schema:
var ClientSchema = new Schema({
clientName: {type: String, required: true},
products: [{ type : mongoose.Schema.ObjectId, ref : 'Product'}],
});
How can I add additional fields to the relationship? For example add field quantity:
var ClientSchema = new Schema({
clientName: {type: String, required: true},
products: [{ type : mongoose.Schema.ObjectId, ref : 'Product', quantity: Number}],
});