How to create MongoSchema dynamically in Nodejs - node.js

I'm following this way.
var mySchema = new Schema({
Id : {type: String},
Name : {type: String}
}, {strict: false});
module.exports = mongoose.model('account', mySchema);
It's working fine, but everytime i restart the server my collection wipe off automatically..
i'm using this way to get collection
const collections = Object.keys(mongoose.connection.collections);
return res.status(200).json({status:true,msg:collections})
After restart the server collection shows empty, What is wrong i'm doing??

Related

How can I access my MongoDB database collections from different projects?

I have node.js server built for mobile apps (server 1), in server 1, I create a collection as below:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var messageSchema = new Schema({
requestNumber: String,
requestedDateTime: String,
reasons: String,
state: String,
hospital: String,
phone: String,
status: {type: String, default: 'Pending'},
latestUpdate: Date,
createdAt: {type: Date, default: Date.now}
});
module.exports = mongoose.model('Requests', messageSchema);
The collection works fine and I am able to access it and post requests to the collection.
Now I am working on another project that has its own server (server 2) (ElectronJS) and I want to retrieve the information posted to the collection above.
I tried to do the following in my server 2:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var hosSchema = new Schema({
hospital: String,
state: String,
reasons: String,
requestedDateTime: String,
requestNumber: String,
status: String,
});
// var hosSchemaModel = mongoose.model('Requests', hosSchema);
// module.exports = hosSchemaModel;
module.exports = mongoose.model('Requests', hosSchema);
My question is, how can I make the the Shema's in server 1 and 2 point to the same collection in the database?
NOTE: I am using mLab to host my database

Nested objects are not update

Allora, I'm using mongoose for the first time and I decided to create 2 schemes: the first one represents a user and the second one represents his enquires. Users have an array of enquires like:
var userSchema = new mongoose.Schema({
name: String,
enquires: { type : [Enquire.schema] , "default" : [] },
});
var enquireSchema = new mongoose.Schema({
status: {type: String, 'default': 'pending'},
enquire: String,
});
I see that if I search for an enquire and update its status, it doesn't update the same enquire on the user's array, meaning that they are different object. I don't want to save an array of IDs as it will be the same as a relational database, so I see only 1 solution which is forgetting about the enquire scheme and use only the User scheme. Is it the way mongoose works? For every relationship do I have to insert everything like nested object?
I think you should use references to achieve what you want to achieve.
For more information on mongoose references and populate see Mongoose Populate documentation.
Try this, It may help you.
User Schema :
var userSchema = new mongoose.Schema({
name: String,
enquires: [{ type : mongoose.Schema.Types.ObjectId , ref : 'Enquiry' }]//array of enquiries
});
var User = mongoose.model('User',userSchema );
module.exports = User;
Enquiry Schema :
var enquireSchema = new mongoose.Schema({
status: {type: String, 'default': 'pending'},
enquire: String,
});
var Enquiry = mongoose.model('Enquiry',enquireSchema );
module.exports = Enquiry ;
Working :
create a new Enquiry.
Push it's ID(_id) into user's enquires array.
var enquiry = new Enquiry();
enquiry.enquire = "Dummy enquiry";//set the enquiry
enquiry.save(function(err,result){
if(!err){
//push 'result._id' into users enquires array
}
});
whenever you update an enquiry, it will be automatically updated in
user's document.
use populate to retrieve user's enquiries.
You can embed sub documents (entity) which has id and is like a document or embed native array like a normal property.
And I think the correct definition for yours is :
var enquireSchema = new mongoose.Schema({
status: {type: String, 'default': 'pending'},
enquire: String,
});
var userSchema = new mongoose.Schema({
name: String,
enquires: { type : [enquireSchema] , "default" : [] },
});
If you use refs in embedded link then there are two separate collections and be like relational db's.

Adding a Static, Complex Object to Mongoose/Passport Schema

I use Mongoose and Passport in my web application for the addition of new users into my MongoDB database. I use Google oauth for registering/signing in. In my user schema, I have the following defined for the google method:
//user.js
var userSchema = mongoose.Schema({
google : {
id : String,
token : String,
access_token : String,
email : String,
name : String,
picture : String,
nameInfo : Object,
}
});
I use the following method for user creation:
//passport.js
var newUser = new User();
//newUser.google.token = token;
newUser.google.name = profile.displayName;
newUser.google.nameInfo = profile._json.name
newUser.google.email = profile.emails[0].value;
newUser.google.id = profile.id;
newUser.google.picture = profile._json.image.url + '0';
newUser.google.access_token = token;
You can see that all this data goes under the "google" array in the top level of my user document. How would I add a new, complex, static array? For example, I want a new array at the top level of document in the following format:
newUser.dogs = ["cats":[]}]
I need this particular format based on a dependency in how users should look in my web code. I will eventually be adding data to the "cats" array, but it needs to start out empty. When I try varations of this, I'm only able to get the top level array - ex: my document looks like:
objectid: 1000,
google: [...],
dogs: []
when I need it to look like:
objectid: 1000,
google: [...],
dogs: [{"cats":[]}]
What do I need to change to my schema, either on the schema design, or the data going into the schema?
You want to set inner embedded docs.
Here it is sample, You can create it like this.
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var Trigger = new Schema({
type : {type: String},
value: {type: Number}
});
var Field = new Schema({
label : {type: String},
type: {type: String},
triggers: [Trigger]
});
var Form = new Schema({
fields : [Field],
user_id : {type: String}
});

Querying embedded documents in MongoDB

I tried to run this query in my nodeJs app
Book.find({'user._id': '545e2915cd91299447fdb8d7'}).populate('user').exec(function(err, books){...}
and it is not working(it returns empty list) but I tried to run this query in cmd using mongo and it was working. Can anyone please help me?
here is scheme for book:
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
path = require('path');
/**
* Book Schema
*/
var BookSchema = new Schema({
title: {
type: String,
trim: true,
required: 'Title is missing'
},
created: {
type: Date,
default: Date.now
},
user: {
type: Schema.ObjectId,
ref: 'User'
}
});
mongoose.model('Book', BookSchema);
Finally I figure where was the problem. Problem was that I created books manually in mongo shell and for some unknown reason it was not working but when I persisted book in app the query with user id was working. I do not understand why(because there should not be any difference when entered in mongo shell and persisted in app) but it works.

Closing DB in Mongoose

I have the following code to insert record in Mongo by using Mongoose.
var mongoose = require('mongoose');
var config = require ('config');
var db = mongoose.createConnection(config.database.address, config.database.dbName);
var strCollectionName = 'category';
var CategorySchema = new mongoose.Schema({
categoryName : {type: String, required: true , unique: true },
categoryTag : {type: String},
categoryDescription : {type: String},
createDate : {type: Date, default: Date.now}
});
var createCategory = function (objCategory)
{
var Category = db.model(strCollectionName, CategorySchema );
var objSchema = new Category(objCategory);
objSchema.save(function (err)
{
if (err)
console.log ("Error");
else
console.log ("Success !!");
});
}
I managed to make it work. But if i try to issue db.close () command inside save it throws error otherwise it is good. My questions is I should not have to close the connection at all ? Will Mongoose automatically takes care it ? - Im worried if the connection pool goes beyond the limit then the entire DB might crash.
To do this properly:
Define your models and tell Mongoose about them at the same time. You can do this before you create the connection.
You were previously telling Mongoose about your schema right when you wanted to use it - you only need to do this once, when you create the schema itself.
You can then open a connection for Mongoose which will work across your whole application (i.e. to use it subsequently, you just have to require('mongoose')):
var mongoose = require('mongoose');
var config = require ('config');
var CategorySchema = new mongoose.Schema({
categoryName : {type: String, required: true , unique: true },
categoryTag : {type: String},
categoryDescription : {type: String},
createDate : {type: Date, default: Date.now}
});
mongoose.model('Category', CategorySchema);
mongoose.connect(config.database.address, config.database.dbName);
If you want to manually create and manage connections you can, using .createConnection as in your example above, but unless you know what you're doing it's better to just use Mongoose's default connection.
To create a category:
// if you're in a different file to where you created your CategorySchema, var these:
var mongoose = require('mongoose'),
Category = mongoose.model("Category");
var createCategory = function (objCategory) {
var newCategory = new Category(objCategory);
newCategory.save(function (err) {
if (err)
console.log ("Error");
else
console.log ("Success !!");
});
}

Resources