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.
Related
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]"
}
]
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.
Learning how to use mongoose, and am trying to design reliably-variable schemas. The app would post to different services (e.g. Twitter, Tumblr) and store them in one collection ("Posts"). There would be some commonalities (e.g. when it was published, or a short summary) but other fields (like post contents, a blog posts's accompanying scripts) would vary.
What's a good way to approach this? Is there a good way to bind together different collections to avoid this in the first place? References/subschemas? Use Schema.Types.Mixed, and reinforce consistency by extending the default methods with safety checks?
// Example pseudo-functioning schemas
const tweetSchema = new mongoose.Schema({
tweetUrl: {type: string, trim: true}
length: Number
});
const blogSchema = new mongoose.Schema({
title: String,
edits: [Date],
slug: { type: String, trim: true},
body: String
});
const postSchema = new mongoose.Schema({
published: Date,
summary: String,
type: String,
contents: blogSchema || tweetSchema
});
Maybe the discriminators could be better option for your case.
Discriminators are a schema inheritance mechanism. They enable you to have multiple models with overlapping schemas on top of the same underlying MongoDB collection.
Sample codes as below
var options = {discriminatorKey: 'contents'};
const postSchema = new mongoose.Schema({
published: Date,
summary: String,
type: String,
}, options);
var Post = mongoose.model('Post', postSchema);
const tweetSchema = new mongoose.Schema({
tweetUrl: {type: string, trim: true}
length: Number
}, options);
var Tweet = Post.discriminator('Tweet', tweetSchema);
const blogSchema = new mongoose.Schema({
title: String,
edits: [Date],
slug: { type: String, trim: true},
body: String
}, options);
var Blog = Post.discriminator('Blog', blogSchema );
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?
Here is my test code which I can not figure out why it isn't working, as it is very similar to test 'populating multiple children of a sub-array at a time'.
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
ObjectId = Schema.ObjectId;
mongoose.connect('mongodb://localhost/testy');
var UserSchema = new Schema({
name: String
});
var MovieSchema = new Schema({
title: String,
tags: [OwnedTagSchema]
});
var TagSchema = new Schema({
name: String
});
var OwnedTagSchema = new Schema({
_name: {type: Schema.ObjectId, ref: 'Tag'},
_owner: {type: Schema.ObjectId, ref: 'User'}
});
var Tag = mongoose.model('Tag', TagSchema),
User = mongoose.model('User', UserSchema),
Movie = mongoose.model('Movie', MovieSchema);
OwnedTag = mongoose.model('OwnedTag', OwnedTagSchema);
User.create({name: 'Johnny'}, function(err, johnny) {
Tag.create({name: 'drama'}, function(err, drama) {
Movie.create({'title': 'Dracula', tags:[{_name: drama._id, _owner: johnny._id}]}, function(movie) {
// runs fine without 'populate'
Movie.find({}).populate('tags._owner').run(function(err, movies) {
console.log(movies);
});
});
})
});
Produced error is
node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
TypeError: Cannot call method 'path' of undefined
at /Users/tema/nok/node_modules/mongoose/lib/model.js:234:44
Update
Got rid from OwnedTag and rewrote MovieSchema like this
var MovieSchema = new Schema({
title: String,
tags: [new Schema({
_name: {type: Schema.ObjectId, ref: 'Tag'},
_owner: {type: Schema.ObjectId, ref: 'User'}
})]
});
Working code https://gist.github.com/1541219
Your variable OwnedTagSchema must be defined before you use it or you'll end up doing basically this:
var MovieSchema = new Schema({
title: String,
tags: [undefined]
});
Move it above MovieSchema definition.
I would expect your code to work, too. Does it work if you put the OwnedTag right in MovieSchema, like so?
var MovieSchema = new Schema({
title: String,
tags: [{
_name: {type: Schema.ObjectId, ref: 'Tag'},
_owner: {type: Schema.ObjectId, ref: 'User'}
}]
});
edit:
var MovieSchema = new Schema({
title: String,
tags: [{ type: Schema.ObjectId, ref: 'OwnedTag' }]
});