Mongoose Schema & Refactoring - mongodb

I. This Works:
//dbModuleSchema.js
var mongoose = require('mongoose');
function getDbModuleSchema() {
var dbModuleSchema = mongoose.Schema({
roles : [rolesSchema] <--------------------------- from local variable
};
///////////////////////////////////
// local variable for roles schema
///////////////////////////////////
var rolesSchema = mongoose.Schema({ //<------------ local variable
name : {type : String},
description : {type: String}
};
return dbModuleSchema;
};
exports.getDbModuleSchema = getDbModuleSchema;
II. This doesn't:
//dbModuleSchema.js
var mongoose = require('mongoose'),
securitySchema = require('./../security/securitySchema');
function getDbModuleSchema() {
var dbModuleSchema = mongoose.Schema({
roles : [securitySchema.getRolesSchema] <-- from separate securitySchema module
}
return dbModuleSchema;
};
exports.getDbModuleSchema = getDbModuleSchema;
//securitySchema.js
var mongoose = require('mongoose');
function getRolesSchema() { //<------ separate securitySchema module
var rolesSchema = mongoose.Schema({
name : {type : String},
description : {type: String}
};
return rolesSchema;
};
exports.getRolesSchema = getRolesSchema;
III. With this as my json:
{
"moduleStyleId" : "style-0",
"name" : "My Dashboard",
"roles" : [{"name" : "Employee", "description" : "Everyone"}]
},
IV. The difference between I & II.
In I, I declared the roles schema in the same module, In II, I refactored it out to it's own seperate module and called its function within the moduleSchema.
Am I not allowed to do that?

Figured it out, the key is to pass the remote module to a variable first:
var mongoose = require('mongoose'),
securitySchema = require('../security/securitySchema');
function getDbModuleSchema() {
var rolesSchema = securitySchema.getRolesSchema(); <--- pass remote schema to variable first
var dbModuleSchema = mongoose.Schema({
roles : [rolesSchema],
};
return dbModuleSchema;
};
exports.getDbModuleSchema = getDbModuleSchema;
Thanks, guys, couldn't have done it w/o "youse"! ;)

Related

ValidationError: user: Cast to Embedded failed for value "[]"

I am trying to insert a new message into the database using expressjs and mongoose.
But I'm getting a ValidationError in the process. The following is printed at the console.
error while storing message ::: ValidationError: user: Cast to
Embedded failed for value "[]" at path "user"
The code is as follows:
socketAPI.io.on('connection', function(socket){
socket.on('chat-sent', function(param) {
ChatUser.find({username : param.username}).then(async (usr)=>{
if(usr){
try{
var mess = new GroupMessage();
mess.group = (await Group.findOne({name : groupName}));
mess.message = param.message;
mess.user = usr;
mess.save((err)=>{
if(err){
console.log('error while storing message ::: '+err);
}
else{
console.log('message succesfully stored');
}
});
}catch(err){
console.log('error collecting group ::: '+err);
}
}
});
socket.emit('group-message-handled', { user : param.username, message : param.message});
});
});
The insertion code makes use of the following models:
var userSchema = new mgoose.Schema({
username : {
type : String,
required : true,
unique : true,
maxlength : [15, 'Too long username. Max 15 allowed']
},
name : String
});
var groupSchema = new mgoose.Schema({
name : {
type : String,
required : true,
unique : true
},
categories : [String]
});
var groupMessageSchema = new mgoose.Schema({
user : userSchema,
group : groupSchema,
message : {
type : String,
required : true,
minlength : 1
}
});
var ChatUser = mgoose.model('ChatUser', userSchema);
var Group = mgoose.model('Group', groupSchema);
var GroupMessage = mgoose.model('GroupMessage', groupMessageSchema);
What causes this error and how can I fix it?

Mongoose auto increment multiple models Initialize connection

I'm using the plugin
mongoose-auto-increment
and it is working fine.
In the description we have to use it like this
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
autoIncrement = require('mongoose-auto-increment');
var connection = mongoose.createConnection("mongodb://localhost/myDatabase");
autoIncrement.initialize(connection);
var bookSchema = new Schema({
author: { type: Schema.Types.ObjectId, ref: 'Author' },
title: String,
genre: String,
publishDate: Date
});
bookSchema.plugin(autoIncrement.plugin, 'Book');
var Book = connection.model('Book', bookSchema);
I have multiple models where i need to auto increment fields
Do i have to initialize in each model the below line
var connection = mongoose.createConnection("mongodb://localhost/myDatabase");
in each model file (where i need increment function)?
I share the solution i implemented myself
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var autoIncrement = require('mongoose-auto-increment');
var connection = mongoose.createConnection("mongodb://localhost/mydatabase");
autoIncrement.initialize(mongoose.connection);
exports.mongoose = mongoose;
exports.Schema = Schema;
exports.autoIncrement = autoIncrement;
and for the schema file
var mong = require('./db');
var Schema = mong.mongoose.Schema;
var autoIncrement = mong.autoIncrement;
var bookSchema = new Schema({
author: { type: Schema.Types.ObjectId, ref: 'Author' },
title: String,
genre: String,
publishDate: Date
});
bookSchema.plugin(autoIncrement.plugin, 'Book');
module.exports = mong.mongoose.model('Book', bookSchema);

Can't seem to import a subdocument

I am trying to import a subdocument into my Express/Mongoose API.
I have the following structure:
models
|-profile
| |-phones.js
|
|-profile.js
Here is the phones.js schema file:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var PhonesSchema = new mongoose.Schema({
phone_number:{ type: String },
phone_type:{ type: Number }
})
module.exports = mongoose.model('PhonesSchema', PhonesSchema);
Here is the profile.js parent document, which resides in the models folder:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var PhonesSchema = require('./profile/phones');
var ProfileSchema = new Schema({
//PROFILE INFO
owner_id: {
type: String,
require: true,
unique: true
},
linkedIn:{
type: String
},
phones:[PhonesSchema],
});
module.exports = mongoose.model('Profile', ProfileSchema);
But it doesn't work.
Any ideas?
seems the issue is more with the fact that you export the model of the PhonesSchema as opposed to the schema. Instead of using
model.exports = mongoose.model('PhonesSchema',PhonesSchema)
you should use:
model.exports = PhonesSchema
ref: https://mongoosejs.com/docs/subdocs.html

MongoDB and mongoose schema

This is model in models.js
var PatientSchema = new mongoose.Schema({
_id : String,
LastName : String,
MiddleName : String,
PatientIntId : String,
Sex : String,
Address1 : String,
City : String,
State : String,
ZipCode : String,
AccountNumber : String,
Ssn : String
});
var PatientInfoMdl = mongoose.model('PatientInfo',PatientSchema);
exports.PatientInfoMdl = PatientInfoMdl;
and my code for accessing data is :
var dbObj = require('../dataBase');
var config = require('../config');<
var moment = require('moment');
var models = require('../models/models');
var orm = require('orm');
var xml2js = require('xml2js');
var fs = require('fs');
var user = models.user;
var PatientInfoMdl = models.PatientInfoMdl;
exports.DisplayUsers = function (req, res) {
var name = '';
dbObj.connect(config.get('mongo'), function () {
PatientInfoMdl.find()({}, function (err, docs) {
if (err)
res.json(err);
else res.render('index', { Patients : docs });
});
});
}
and I am not getting data and what is my mistake?
My mistake is not following the naming conventions of collections in mongoDB.
Is there a convention to name collection in MongoDB?
For example:
Controller.js
var mongoose = require('mongoose');
var User = mongoose.model('User');
module.exports = {
show: function(req, res) {
User.find({}, function(err, users) {
res.render('main', {users: users});
})
}
}
Models:User.js
// require mongoose
var mongoose = require('mongoose');
// create the UserSchema
var UserSchema = new mongoose.Schema({
name: String
})
// register the schema as a model
var User = mongoose.model('User', UserSchema);
module.exports = {User}
routes.js
// here we load the Quote model that we created on the server.js page
var mongoose = require('mongoose');
var User = mongoose.model('User');
// import users
var users = require('../controllers/users.js');
module.exports = function(app) {
app.get('/', function(req, res) {
res.send("Hello");
})
app.get('/user',function(req,res){
users.show(req,res);
})
}

MongoDB 2dSphere indexing embedded document

var LocationSchema = new mongoose.Schema({'type': { type: String }, coordinates : []},{_id:false});
var EventsSchema = new mongoose.Schema({
title:String,
status:String,
location:[new mongoose.Schema({
ll:[LocationSchema],
type:String
},{_id:false})] ,
});
Code to add a document:
function (req,res) {
var event = new Events();
var sLoc = new Location();
var dLoc = new Location();
event.title = req.body.title;
event.startdate = req.body.startdate;
sLoc.coordinates.push(parseFloat(req.body.slong));
sLoc.coordinates.push(parseFloat(req.body.slat));
sLoc.type= "Point";
dLoc.coordinates.push(parseFloat(req.body.dlong));
dLoc.coordinates.push(parseFloat(req.body.dlat));
dLoc.type = "Point";
event.location.push({ll:sLoc,type:"s"});
event.location.push({ll:dLoc,type:"d"});
event.save();
}
When I try to save the document, it give an error -- "Can't extract geo keys from object, malformed geometry?:{ 0: { type: [ -122.1251274, 37.4096933 ] } }"
I am making above query in mongoosejs with nodejs
Please let me know what I am doing wrong.