Relationship between two schemas in mongodb using mongoose - node.js

I have two schemas first one is countrySchema which has country id and name:
Below is the schema code:
var countrySchema = new Schema({
country_id:String,
country_name:String
});
var countryArray = mongoose.model('countryArray',countrySchema);
Another schema is stateSchema which has state id and state name:
below is the schema code:
var Schema = mongoose.Schema;
var stateSchema = new Schema({
state_id:String,
state_name:String,
});
var states = mongoose.model('states',stateSchema);
Now, in stateSchema i want to have state_id, country_id which is actually coming from the countrySchema and the state_name. How do I do this ?

You can add the country_id as follows and refer the country module in your state module with ObjectId of the country. Then you have to use the objectId which created by mongoose for the particular country as the country_id of stateSchema.
countrySchema
var countrySchema = new Schema({
_id:Schema.Types.ObjectId,
country_id:String,
country_name:String
});
var countryArray = mongoose.model('countryArray',countrySchema);
stateSchema
var stateSchema = new Schema({
_id:Schema.Types.ObjectId,
state_id:String,
country_id: {Schema.Types.ObjectId, ref:'countryArray'},
state_name:String,
});

Try This One..
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var countrySchema = new Schema({
country_id:String,
country_name:String
});
var countryArray = mongoose.model('countryArray',countrySchema);
var stateSchema = new Schema({
state_id:String,
state_name:String,
country: { type: Schema.Types.ObjectId, ref: 'countryArray' },
});
var states = mongoose.model('states',stateSchema);

Related

Mongoose _id to unit64

I need a unit64 ID in my MongoDB database. ObjectIds are 96 bits.
I have seen the answer here that one way to do it is to add a few constant characters to the beginning of the ID. But how d I achieve this in Mongoose?
Suppose that I have a schema like this:
var mongoose = require('mongoose');
var schema = new mongoose.Schema({
_id: {
???
},
});
I ended up using nanoid for now:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const { customAlphabet } = require('nanoid');
const alphabet = '123456789';
const nanoid = customAlphabet(alphabet, 19); //from 11...111 to 99...999
const mySchema = new Schema({
int_id: {
type: String,
unique: true,
default: () => nanoid()
},
});

Mongoose : Types referring to other models

I've this:
models/record.js
var mongoose = require("mongoose");
var RecordSchema = new mongoose.Schema({
address : require("./address").Address
});
var Record = mongoose.model('Record', RecordSchema);
module.exports = {
Record: Record
}
models/address.js
var mongoose = require("mongoose");
var AddressSchema = new mongoose.Schema(
{
streetLine1: String,
streetLine2: String,
city: String,
stateOrCounty: String,
postCode: String,
country: require("./country").Country
});
var Address = mongoose.model('Address', AddressSchema);
module.exports = {
Address: Address
}
models/country.js
var mongoose = require("mongoose");
var CountrySchema = new mongoose.Schema({
name: String,
areaCode: Number
});
var Country = mongoose.model('Country', CountrySchema);
module.exports = {
Country: Country
}
It's actually showing this error:
TypeError: Undefined type Model at country
Did you try nesting Schemas? You can only nest using refs or arrays.
I am trying to create a model where few types is another model. How to archive this ?
The problem here is that you are exporting a model from country.js and using the same by requiring in the address schema creation. While creating nested schemas, the value for a property should be a schema Object and not a model.
Change your country.js to:
var mongoose = require("mongoose");
var CountrySchema = new mongoose.Schema({
name: String,
areaCode: Number
});
module.exports = {
Country: CountrySchema
}

Aggregation and populate using mongoose

I have two collection like this:
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var GradeSchema = new Schema({
gID: { type: Number, ref: 'User'},
grade: Number,
created_at: Date,
updated_at: Date,
type: Number
});
var Grade = mongoose.model('Grade', GradeSchema);
module.exports=Grade;
and:
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var UserSchema = new Schema({
name: String,
lastName:String,
uID: { type: Number,ref:'Grade' },
phone: String
});
var User = mongoose.model('User', UserSchema);
module.exports=User;
how can i first aggregate and then populate to have both collection information??
i used this command using $lookup in mongodb and it return my suggested documents:
db.grades.aggregate([{$lookup
{from:"users",localField:"gID",foreignField:"uID",as: "result"}},{$match:
{"type":0}},{"$sort":{"grade":-1}}])
but when i used this in mongoose the "result" is [] and connection to user collection is failed:
Grade.aggregate([{"$lookup":
{"from":"User","localField":"gID","foreignField":"uID","as": "result"}},
{"$match":{"type":3}},{"$sort":{"grade":-1}}]).exec(function(err, data)
{console.log(data);});

is it possible to reference a subdocument schema in mongoose?

is it possible to reference a sub document schema in mongoose ?
just like below
var sectionSchema = mongoose.Schema(
{
id:{type:String,required:true},
name:{type:String,required:true}
});
var courseSchema = mongoose.Schema(
{
id:{type:String,required:true},
name:{type:String,required:true},
sections:[sectionSchema]
});
var studentSchema = mongoose.Schema(
{
id:{type:String,required:true},
name:{type:String,required:true},
course:{type:mongoose.Schema.Types.ObjectId,ref: 'courseSchema'},
section:{type:mongoose.Schema.Types.ObjectId,ref: 'sectionSchema'},
contactnumber:{type:String,required:true},
parentname:{type:String,required:true}
});
var schoolSchema = mongoose.Schema(
{
id:{type:String,required:true},
name:{type:String,required:true,unique:true},
address:{type:String,required:true},
year:{type:String,required:true},
contactnumber:{type:String,required:true},
courses:[courseSchema],
students:[studentSchema]
});
var School = mongoose.model('School',schoolSchema);
in the above model i have section inside course which is inside school document.
i have students schema which is inside school document i want course to point to course schema and section to point to section schema.so is it possible to refer a sub document schema in mongoose.

Mongoose Sub-documents on separate files, how to embed them

I'm defining my application models and i have separate files for each model that i'm defining, my question is, i need to create a model that use a sub-document, but that's on another file, how can i use that Schema on my model ? what i mean is that all examples i've seen declare the Child model and the Parent on the same file, example:
var childSchema = new Schema({ name: 'string' });
var parentSchema = new Schema({
children: [childSchema]
});
I have one file called user.js that defines the user model :
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema({
_id : Schema.Types.ObjectId,
username : String,
});
module.exports = mongoose.model( 'User', userSchema );
And on another file called sport.js i have the other model definition for the sports:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var sportSchema = new Schema({
_id : Schema.Types.ObjectId,
name : String
});
module.exports = mongoose.model( 'Sport', sportSchema );
So on my user model I need to define a field for the sports that the user will follow, but i do not know how to define that sub-document since the sports definition is on another file, I tried this:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var SportsModel = require('sport');
var userSchema = new Schema({
_id : Schema.Types.ObjectId,
username : String,
sports : [SportsModel]
});
module.exports = mongoose.model( 'User', userSchema );
But i'm not sure if that's the correct way since what i'm exporting is the model, not the Schema.
Thanks in advance, i want to define each model on separate files to maintain order.
You can access a Model's schema via its schema property. So this should work:
var userSchema = new Schema({
_id : Schema.Types.ObjectId,
username : String,
sports : [SportsModel.schema]
});
Use ref
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema({
_id : Schema.Types.ObjectId,
username: String,
sports : [{ type: Schema.Types.ObjectId, ref: 'Sport' }]
});
module.exports = mongoose.model('User', userSchema);
Incidentally, with ref, you can use .populate('sports') when you query, and mongoose will expand those types for you.

Resources