Dynamic schema keys in Mongoose - node.js

I have a simple requirement to get dynamic keys and their values to insert in mongo.
something like this:
[
{"key1": "val1"},
{"key2": "val2"}
]
For this I have created schema as :
As I read about [Schema.Types.Mixed],but it only makes datatype of assigned values dynamic ,not the key in my case.
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var myschema = new Schema({ key: [Schema.Types.Mixed] });
module.exports = mongoose.model('DataCollection', myschema);
Can anybody point , whtat is it that I am missing.
This is my output,which shows blank value.
Thanks in advance.

I don't think it is possible to literally have a dynamic key as that defeats the purpose of a schema, but you could do something like this:
var KeyValueSchema = new Schema({
key : String,
value : String
});
module.exports = mongoose.model('KeyValueCollection', KeyValueSchema);
Alternatively using the Mixed data type you could store an entire JSON object. For example using this schema:
var mySchema = new Schema({
data : Schema.Types.Mixed
});
module.exports = mongoose.model('DataCollection', mySchema);
You could insert like:
.post(function(req, res) {
var collection = new DataCollection();
collection.data = {'key' : 'value'};
collection.save(function(err) {
if(err) res.send(err);
res.json({message:'Data saved to collection.'});
});
});

Related

How to implement more than one collection in get() function?

My model university.js
const mongoose = require('mongoose');
const UniversitySchema = mongoose.Schema({
worldranking:String,
countryranking:String,
universityname:String,
bachelorprogram:String,
masterprogram:String,
phdprogram:String,
country:String
},{collection:'us'});
const University =module.exports = mongoose.model('University',UniversitySchema);
My route.js
const express = require('express');
const router = express.Router();
const University = require('../models/university');
//retrieving data
//router.get('/universities',(req,res,next)=>{
// University.find(function(err,universities){
// if(err)
// {
// res.json(err);
//}
// res.json(universities);
//});
//});
router.get('/usa',function(req,res,next){
University.find()
.then(function(doc){
res.json({universities:doc});
});
});
module.exports= router;
How to implement multiple collections in this get() function? I put my collection name in the model. Please help me with a solution to call multiple collections in get() function.
Here is Example to use multiple collection names for one schema:
const coordinateSchema = new Schema({
lat: String,
longt: String,
name: String
}, {collection: 'WeatherCollection'});
const windSchema = new Schema({
windGust: String,
windDirection: String,
windSpeed: String
}, {collection: 'WeatherCollection'});
//Then define discriminator field for schemas:
const baseOptions = {
discriminatorKey: '__type',
collection: 'WeatherCollection'
};
//Define base model, then define other model objects based on this model:
const Base = mongoose.model('Base', new Schema({}, baseOptions));
const CoordinateModel = Base.discriminator('CoordinateModel', coordinateSchema);
const WindModel = Base.discriminator('WindModel', windSchema);
//Query normally and you get result of specific schema you are querying:
mongoose.model('CoordinateModel').find({}).then((a)=>console.log(a));
In Short,
In mongoose you can do something like this:
var users = mongoose.model('User', loginUserSchema, 'users');
var registerUser = mongoose.model('Registered', registerUserSchema, 'users');
This two schemas will save on the 'users' collection.
For more information you can refer to the documentation: http://mongoosejs.com/docs/api.html#index_Mongoose-model or you can see the following gist it might help.
Hope this may help you. You need to modify according to your requirements.

Querying result from mongoose using dynamic model.find

I need to find the results of a query with mongoose find({}) method in Node.js with a variable containing model name.
var adSchema = new Schema({ schema defination });
var Ad = mongoose.model('Ad', adSchema);
var variableName = 'Ad';
variableName.find({}).exec(function (err, adObj) {});
Is it possible or not?
Thanks in advance
You should be able to do that when calling model with just the name like so
mongoose.model('Ad').find({}).exec(function (err, adObj) {});
See here for the corresponding part of the official docs
Try this:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var anySchema = new Schema({
fieldname: String
});
var Test = mongoose.model('Test', anySchema);
Test.find({}).exec(function(err,result){});

express mongoose router query

Am trying to return all item with store name ,using the conditional query method ,but the it return all items insteads ,i tried the maybe my logic is wrong
because what am trying to achieve it return all data that where store name is ,is say max mart
route('api/discount/?store=storename)
and
router.route('/discount/:store')
.get(function(req,res){
Discount.find({store:req.params.store}, function(err, discount){
if (err)
res.send(err);
res.json(discount);
});
})
so i called api/discount/store ,but this return all the data ,does not make any queries
schema model
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var DiscountSchema = new Schema({
store: String,
location : String,
discount : Number,
});
module.exports = mongoose.model('Bear', DiscountSchema);
You made a wrong query. You have a route to /discounts/:discount_id and you query for store:req.params.store, and a req.params.store doesn't exists, just a discount_id

Accessing subdocument properties in mongoose

I am using a MEAN stack to build this application.
Here is my subject.js schema:
var mongoose = require('mongoose');
var schema = mongoose.Schema;
var topics = require('./topic');
var subjectSchema = new schema({
_category : {
type: String,
default: ""
},
topics: [topics.schema]
});
module.exports = mongoose.model('Subject', subjectSchema);
and my topics.js schema:
var mongoose = require('mongoose');
var schema = mongoose.Schema;
var otherstuff = require('./otherstuff');
var otherstuff2 = require('./otherstuff2');
var topicSchema = new schema ({
title: String,
otherstuff: [mongoose.model('otherstuff').schema],
otherstuff2: [mongoose.model('otherstuff2').schema]
});
module.exports = mongoose.model('Topic', topicSchema);
What I am having difficulty with is how to access my topicSchema to populate it with forms from my front end.
I can save information to the subjectSchema, but not the sub documents.
I have tried using this as outlined in another article:
var Subject = mongoose.model('Subject', subjectSchema);
Subject.find({}).populate('subjects[0].topics[0].title').exec(function(err, subjects) {
console.log(subjects[0].topics[0].title);
});
But I continue to get TypeError: Cannot read property 'title' of undefined. How do I access the title property?
populate in mongoose is used to populate referenced documents, that are marked with ref attribute (see more info in the docs). Sub-documents on the other hand are available when do a simple query because they are actually an array of custom objects, so if you remove the populate method your query will work as expected:
Subject.find({}).exec(function(err, subjects) {
console.log(subjects[0].topics[0].title);
});

What are Mongoose (Nodejs) pluralization rules?

I am a newbie to the Node.js, Mongoose and Expressjs. I have tried to create a table "feedbackdata" using the Mongoose in MongoDB via the following code. But it is created as "feedbackdata*s*". By Googling, I found that the Mongoose uses pluralization rules. Anyone please help me to remove the pluralization rules? or how my code should be for the "feedbackdata" table?
Below is my code:
app.post("/save",function(req,res){
mongoose.connect('mongodb://localhost/profiledb');
mongoose.connection.on("open", function(){
console.log("mongo connected \n");
});
// defining schemar variables
Schema = mongoose.Schema,
ObjectId = Schema.ObjectId;
// define schema for the feedbackdata table
var feedback_schema = new Schema({
_id: String,
url:String,
username:String,
email:String,
subscribe:String,
types:String,
created_date: { type: Date, default: Date.now },
comments: String
});
// accessing feeback model object
var feedback_table = mongoose.model('feedbackdata', feedback_schema);
var tableObj = new feedback_table();
var URL = req.param('url');
var name = req.param('name');
var email = req.param('email');
var subscribe = req.param('subscribe');
var choices = req.param('choices');
var html = req.param('html');
var receipt = req.param('receipt');
var feedbackcontent = req.param('feedbackcontent');
tableObj._id = 3;
tableObj.url = URL;
tableObj.username = name;
tableObj.email = email;
tableObj.subscribe = subscribe;
tableObj.types = choices;
tableObj.comments = feedbackcontent;
tableObj.save(function (err){
if(err) { throw err; }else{
console.log("Saved!");
}
mongoose.disconnect();
})
res.write("<div style='text-align:center;color:green;font-weight:bold;'>The above values saved successfully! <br><a href='/start'>Go back to feedback form</a></div>");
res.end();
});
The pluralization rules are in this file: https://github.com/LearnBoost/mongoose/blob/master/lib/utils.js
You can add your schema name to the 'uncountables' list, then mongoose will not pluralize your schema name.
Provide the name for the collection in options while creating schema object, then Mongoose will not do pluralize your schema name.
e.g.
var schemaObj = new mongoose.Schema(
{
fields:Schema.Type
}, { collection: 'collection_name'});
For more Info: http://mongoosejs.com/docs/guide.html#collection
The pluralization rules is here to ensure a specific naming convention.
The collection name should be plural, all lowercase and without spacing.
What are naming conventions for MongoDB?
I think you should ask yourself if you want to follow the main rule (ensured by mongoose as a default behavior) or get rid of it.
What are the perks ? What are the good points ?
You design first what is an user (User model) and then you store users into a collection. It totally make sense.
Your call.
If you ask yourself how to get the final name of the collection after the pluralization :
const newName = mongoose.pluralize()('User');

Resources