Can't seem to import a subdocument - mongodb

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

Related

MERN stack : Express api returning empty data , but the data is already present in mongodb

I am new to the MERN stack, and I have been trying to access my collections in MongoDB.
Here is the code for the router, view bookings:
/*This is router file*/
var mongoose = require('mongoose');
const express = require('express');
const bodyParser = require('body-parser')
let book = require('../models/BookTravel');
const router = require('express').Router()
router.use(express.json())
router.route('/').get((req, res) => {
// Company.aggregate({companyId})
book.find()
.then((result) => {
console.log(result)
return res.status(200).json(result)
})
})
module.exports = router;
/*
* this is for model
*/
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const TravelSchema = new Schema({
firstname:{
type: String,
required: true
},
bookingId:{
type: String,
required: true
},
lastname:{
type: String,
required: true
},
startcity:{
type: String,
required: true
}
})
const travel = mongoose.model('travel', TravelSchema)
module.exports = travel;
////in app.js file
const viewBookings = require('./routes/viewBookings');
app.use('/viewBookings', viewBookings)
The postman is also giving empty result.
What am I missing out ? Is it not possible to access the already existing collection with this method ?
You are missing some code in the router file.
for example! If you want to get data from a database
you can simply use like below this
.......
router.get("/",async (req,res)=>
{
try{
const result = await book.find();
res.status(200).json({"message" : result})
}
catch(error)
{
console.log(error)
}
})
......

mongoose not fetching data

I am trying to fetch all users from a MongoDB database. However for some reason recently the request did not fetch anything.
Here is the code in which I try to fetch the data:
app.get('/api/allusers', (req, res) => {
Employee.find()
.then(rettrievedData => {
res.json(rettrievedData)
});
});
Here is the mongoose model:
const mongoose = require('mongoose');
const employeeSchema = mongoose.Schema({
name: { type: String },
surName: { type: String },
mail: { type: String },
phone: { type: String },
});
module.exports = mongoose.model('Employee', employeeSchema, 'employee.employees');
Here is the code for connecting to Mongo
mongoose.connect("mongodb+srv://Kiril:xxxxxxxxxxxxx#cluster0-owdfy.mongodb.net/employee?retryWrites=true&w=majority")
.then(() => {
console.log("Connected")
})
Also I have checked that there is data in the database, but for some reason the Employee.find() does not retrieve anything. What can be reason?
Thanks in advance.
why you are adding 'employee.employyes' when you creating your model
try to export the model without it
module.exports = mongoose.model('Employee', employeeSchema)
or better
exports.Employee = mongoose.model('Employee', employeeSchema)
and require it where you want to use it
const Employee = require('path to the schema file')

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

Mongoose Schema & Refactoring

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

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