Mongoose : Types referring to other models - node.js

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
}

Related

How do I update the existing documents' schema?

I'm using mongoose to do some MongoDB operations.
At the beginning the category was number,
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const sampleSchema = new Schema({
category: {
type: Number,
}
})
module.exports = mongoose.model("SampleSchema", sampleSchema);
Now the category changed to String, So I changed the model like this
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const sampleSchema = new Schema({
category: {
type: String,
}
})
module.exports = mongoose.model("SampleSchema", sampleSchema);
The problem is, I have already inserted 200 records into this collection. Is there any way to update the category value with a string and change its type to string?
Please get All data by query and update it one by one in loop.
Like:
db.tableName.find( { 'status' : { $type : 1 } } ).forEach( function (val) {
val.status = new String(val.status);
db.tableName.save(val);
});
I changed the category to mixed, that's working fine with numbers and string.
Thanks for the help #prasad_

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()
},
});

Relationship between two schemas in mongodb using mongoose

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);

Multiple schema in a file not working

I have two schema in singel schema.js file
var mongoose = require('mongoose');
var user = new mongoose.Schema({
name: String,
add: String,
role: String
});
var Organizationn = new mongoose.Schema({
name: String,
add: String,
name:String
});
module.exports = {
user: user,
Organizationn: Organizationn
};
accessing it like
var models = require("../models/schema");
models.user.findOne()
it says findone is not a function
whereas If i use singel user in a file it is working.
I have gone through this link and did export like above
cant get data from database after multiple schema declared (mongoose + express + mongodb
but not working
any idea?
Thanks
With the help of #anthony I figure out the issue
I need to do the below
module.exports = {
user: mongoose.model('user', user),,
Organizationn: mongoose.model('Organizationn', Organizationn)
};
If you exports more than one file than you will have to import with curly braces { schema1 }
var mongoose = require('mongoose');
var user = new mongoose.Schema({
name: String,
add: String,
role: String
});
var organization = new mongoose.Schema({
name: String,
add: String,
name:String
});
const userSchema = mongoose.model('users', user),
const organizationSchema = mongoose.model('organizations', organization)
module.exports = { User: userSchema, Organization: organizationSchema }
and then import
var { User } = require("../models/schema");
var { Organization } = require("../models/schema");
User.findOne()
Organization.findOne()
Try to look at it in this abstract way:
A mongoose.Schema is basically just an object.
A mongoose.model is a class that you customize with your schema object.
In other words, mongoose.model has all the database functions attached to it, the schema by itself doesn't.

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);});

Resources