Register Schema - Mongo Relationship - node.js

im new working with mongoDB and node.js im trying to creat a relation between two models applications and contactsapp
applicationsModel
'use strict'
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const contactapp = mongoose.model('ContactApp');
const ApplicationsSchema = Schema({
application_code: String,
name: String,
comments: String,
version: String,
developer: String,
url: String,
active: Boolean,
press_package: String,
pad_file: String,
image: String,
category: [String],
contacts: [{ type: Schema.ObjectId, ref: "ContactApp" }]
});
module.exports = mongoose.model('Applications', ApplicationsSchema);
contactsappModel
'use strict'
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ContactappSchema = Schema({
fullname: String,
avatar: String,
company: String,
jobTitle: String,
email: String,
phone: String,
sex: String,
country: String,
channel: String,
website_url: String,
linkedin_url: String,
xing_url: String,
notes: String,
active: Boolean
});
module.exports = mongoose.model('ContactApp',ContactappSchema);
but when the console give me the error Schema hasn't been registered for model "ContactApp".

Your app probably loads applicationsModel.js before contactsappModel.js, so the ContactApp model hasn't been registered yet when this line is executed:
const contactapp = mongoose.model('ContactApp');
Since you're not using the contactapp variable anyway, try removing that line entirely.

Related

TypeError: Invalid schema configuration: `model` is not a valid type within the array `category`

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.

How do I set up schema for a song with multiple artist?

I am creating an application to display new music. On the landing page there will be a section that displays the most recently uploaded music. When a user clicks on the song, it will take them to a show template which will display Artist name, title, video, description and artist(s) social medias.
I also want a section that displays all artist included in that song. When a user clicks an artist name it will render a page with all songs that artist has. So I am having an issue creating a schema since one song can have multiple artist.
My old schema was designed to take input from a form and displayed it without any relationships to the artist.
With my new schemas I am trying to create relationships between the artist(s) and song.
Old Schema
const mongoose = require("mongoose");
artistSchema = new mongoose.Schema({
name: String,
title: String,
image: String,
content: String,
description: String,
category: String,
soundcloud: String,
scName: String,
instagram: String,
igName: String,
twitter: String,
twName: String
});
module.exports = mongoose.model("Artist", artistSchema);
New Schemas
const mongoose = require("mongoose");
artistSchema = new mongoose.Schema({
name: String,
social: schema.ObjectId,
music: schema.ObjectId
});
module.exports = mongoose.model("Artist", artistSchema);
const mongoose = require("mongoose");
socialSchema = new mongoose.Schema({
soundcloud: String,
scName: String,
instagram: String,
igName: String,
twitter: String,
twName: String
});
module.exports = mongoose.model("Social", socialSchema);
const mongoose = require("mongoose");
musicSchema = new mongoose.Schema({
title: String,
image: String,
content: String,
description: String,
category: String
});
module.exports = mongoose.model("Music", musicSchema);
After looking around for a while I found some documentation related to what I am trying to do. https://gist.github.com/fwielstra/1025038
So my question is if my schema is set up properly and if I will run into any problems if I continue following the Github documentation.
look into, one to many relationship. one song relates to many artists.
const mongoose = require("mongoose");
musicSchema = new mongoose.Schema({
title: String,
image: String,
content: String,
description: String,
category: String,
artists: [
{
type: Schema.Types.ObjectId,
ref: "Users"
}
]
});
module.exports = mongoose.model("Music", musicSchema);
voters: [
{
type: Schema.Types.ObjectId,
ref: "someModel[artists model]"
}
]

ReferenceError: <model> is not defined

I have several schemas defined. Here's one that works fine:
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var NewsSchema = new Schema({
name: String,
route: String,
remoteURL: String,
articles: [{title: String, link: String, Image: String, contentSnippet: String}],
retrieved: Date,
dormant: { type: Boolean, default: false}
});
module.exports = mongoose.model('News', NewsSchema);
Here's a second one that's nearly identical:
var mongoose = require('mongoose'),
Schema = mongoose.Schema
// NewsSchema = new Schema({ name: String });
var ArticlesSchema = new Schema({
title: String,
link: String,
pubDate: Date,
image: String,
contentSnippet: String,
sourceName: String
// sourceId: [ {type: Schema.Types.ObjectId, ref: NewsSchema}]
});
module.exports = mongoose.model('Articles', ArticlesSchema);
I've loaded both of the modules at the top of my program, along with a bunch of other stuff like this:
players = require('./app/models/players'),
articles = require('./app/models/articles'),
If I create an instance of the first one with something like:
var player = new Players();
But if I try to create an instance of the second one with:
var item = new Articles();
I receive the error in the subject. In tracing the code I can see that the modules are in scope, so I don't believe it's something stupid like redefining a variable or something like that.
Any ideas?
There is a missing quote mark, so
Instead of
sourceId: [ {type: Schema.Types.ObjectId, ref: NewsSchema}]
use
sourceId: [ {type: Schema.Types.ObjectId, ref: 'NewsSchema'}]
would solve your problem.

One to Many relationship in Express Models using mongoDB

This is doctors.js model:
var mongoose = require('mongoose'), Schema = mongoose.Schema;
var Patient = require('./patient.js');
var doctorSchema = mongoose.Schema({
firstName: String,
lastName: String,
qualifications: String,
photo: Buffer,
_patients: [{ type: Schema.Types.ObjectId, ref: 'Patient' }]
});
var Doctor = mongoose.model('Doctor', doctorSchema);
module.exports = Doctor;
This is patients.js model:
var mongoose = require('mongoose');
var Doctor = require('./doctor.js');
var patientSchema = mongoose.Schema({
firstName: String,
lastName: String,
dob: String,
gender: String,
primaryDiagnosis: String,
duration: String,
_doctorIncharge: {type: Number, ref: 'Doctor'},
hospitalNumber: String,
photo: Buffer
});
var Patient = mongoose.model('Patient', patientSchema);
module.exports = Patient;
Is this the way to make a one to many relationship work?

How to reference another schema in my Mongoose schema?

I'm building a Mongoose schema for a dating app.
I want each person document to contain a reference to all the events they've been to, where events is another schema with its own models in the system. How can I describe this in the schema?
var personSchema = mongoose.Schema({
firstname: String,
lastname: String,
email: String,
gender: {type: String, enum: ["Male", "Female"]}
dob: Date,
city: String,
interests: [interestsSchema],
eventsAttended: ???
});
You can do so by using Population
Population is the process of automatically replacing the specified
paths in the document with document(s) from other collection(s). We
may populate a single document, multiple documents, plain object,
multiple plain objects, or all objects returned from a query.
Suppose your Event Schema is defined as follows:
var mongoose = require('mongoose')
, Schema = mongoose.Schema
var eventSchema = Schema({
title : String,
location : String,
startDate : Date,
endDate : Date
});
var personSchema = Schema({
firstname: String,
lastname: String,
email: String,
gender: {type: String, enum: ["Male", "Female"]}
dob: Date,
city: String,
interests: [interestsSchema],
eventsAttended: [{ type: Schema.Types.ObjectId, ref: 'Event' }]
});
var Event = mongoose.model('Event', eventSchema);
var Person = mongoose.model('Person', personSchema);
To show how populate is used, first create a person object,
aaron = new Person({firstname: 'Aaron'})
and an event object,
event1 = new Event({title: 'Hackathon', location: 'foo'}):
aaron.eventsAttended.push(event1);
aaron.save(callback);
Then, when you make your query, you can populate references like this:
Person
.findOne({ firstname: 'Aaron' })
.populate('eventsAttended') // only works if we pushed refs to person.eventsAttended
.exec(function(err, person) {
if (err) return handleError(err);
console.log(person);
});
To reference the ObjectId of one table in another table refer below code
const mongoose = require('mongoose'),
Schema=mongoose.Schema;
const otpSchema = new mongoose.Schema({
otpNumber:{
type: String,
required: true,
minlength: 6,
maxlength: 6
},
user:{
type: Schema.Types.ObjectId,
ref: 'User'
}
});
const Otp = mongoose.model('Otp',otpSchema);
// Joi Schema For Otp
function validateOtp(otp) {
const schema = Joi.object({
otpNumber: Joi.string().max(6).required(),
userId: Joi.objectId(), // to validate objectId we used 'joi-objectid' npm package
motive: Joi.string().required(),
isUsed: Joi.boolean().required(),
expiresAt: Joi.Date().required()
});
// async validate function for otp
return schema.validateAsync(otp);
}
exports.Otp = Otp;
exports.validateOtp = validateOtp;
List item
var personSchema = mongoose.Schema({
firstname: String,
lastname: String,
email: String,
gender: {
type: String,
enum: ["Male", "Female"]
}
dob: Date,
city: String,
interests: [interestsSchema],
eventsAttended[{
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: "Place"
}],
**//ref:"Places"...you have put the other model name**
*OR*
eventsAttended[{
type: mongoose.Types.ObjectId,
required: true,
ref: "Place"
}],
});

Resources