Express js and Mongo DB database definition [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I started learning node these days and Im using Express js framework.
I found this great tutorial from Christophe Coenraets with all stuff I need since I have a little bit experience in Backbone js.
The thing that's confusing me the most in Node js is working with databases . (I'm only familiar with MYSQL since i was using PHP)
For example in this tutorial , in this file
https://github.com/ccoenraets/nodecellar/blob/master/routes/wines.js
He use "populateDB" function to populate the database for the first time whit some doomy data when app is started,
Now since I was using PHP , I what to do the same thing I was doing there , I want to create database structure or something like shell so I can have an image in my head to to represent the data , for example I saw some example is "mongoose" module "mongo db object modeling" that there are some things like "Schema" or something like that .
Can somebody explain me right logic on working with databases in Node js, how you start when you are creating your app, the process and stuff? its little bit confusing to start working and to dont know from the start how the database will look like.
Tnx a lot ! :)

The thing about NoSQL databases like mongodb is that you no longer have the traditional columns, rows, and tables. We now have fields, documents and collections. See SQL to MongoDB Mapping Chart
Mongoose is a framework that provides a schema-based solution to modeling your application data. It's not necessary to use but does provide you with the option of having predefined schemas and models similar to that of SQL schemas, instead of inserting straight up JSON into the collections. See Why does mongoose use schema when mongodb's benefit is supposed to be that it's schema-less? for more details.
For example:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var Schema = mongoose.Schema;
var catSchema = new Schema({ //cat schema
name: String,
age: Number
});
var Cat = mongoose.model('Cat', catSchema); //cat model
var kitty = new Cat({ name: 'Zildjian', age: 5 }); //kitty is a cat
kitty.save(function (err) {
if (err) // ...
console.log('Error saving to the database');
});
...and now you have a kitty saved in your mongodb
So to start: download and install mongod and mongodb, npm install mongoose, create your schema and model via mongoose.
To query/find/retrieve documents/rows from the database, use the model.find(), ex:
// named Zildjian and at least 5
Cat.find({ name: 'Zildjian', age: { $gte: 5 }});
For more details, please see model.find API

Related

collections (table names in other dbs) in mongodb

I created an express server for connection to my mongodb. Before I start, everything works fine.
But I dont understand some things.
I made a collection in my mongodb, projects (with an 's' at the end)
In my code I made a project.model.js like: const Project = mongoose.model("Project", ...) module.exports = Project
Elsewhere I have db.project = require("./project.model");
Everything works like a harm, creating, updating, deleting. But I dont understand. My collections in my mongodb don't have the same name. The names are Users, Materials and in my code I use user, material. Maybe it is a stupid question but how does this work?
It is the default behavior of mongoose to convert singular to plural model names.
To fix your issue & to convert your model name from plural to singular or any other name, You can write your code as shown below
const Project = mongoose.model("Project", ProjectSchema, 'Project')
module.exports = Project
Now you could see the collection name as Project.
The third parameter in the mongoose.model is the collection name.

Auto-generate model definitions from existing ArangoDB database

I'm using ArangoDB 3.4 and planning to use an MVC framework like Backbone.js (or whatever is recommended). Is there a way to auto-generate the models from the existing database to reduce the amount of boilerplate code I have to write by hand?
For example, I am looking at the aye-aye TodoMVC demo. It has this model:
const joi = require('joi');
exports.Model = {
_key: joi.string().optional(),
_id: joi.string().optional(),
_rev: joi.string().optional(),
completed: joi.boolean().optional(),
order: joi.number().optional(),
title: joi.string().optional()
};
Writing a few by hand is no problem. My database will ultimately require many of these models. Are there any tools that I can use with ArangoDB that will help automate this by producing scaffold code?
What I have in mind is possibly something like Python's inspectdb command:
http://docs.djangoproject.com/en/dev/ref/django-admin/#inspectdb
inspectdb
Introspects the database tables in the database pointed-to by the DATABASE_NAME setting and outputs a Django model module (a models.py file) to standard output.
Use this if you have a legacy database with which you'd like to use Django. The script will inspect the database and create a model for each table within it.
As you might expect, the created models will have an attribute for every field in the table.
If there are entirely different approaches to doing this with ArangoDB and javascript please point me in the right direction.
django-admin inspectdb [table [table ...]] targets relational databases where tables have schema and because of that it's possible to generate model
ArangoDB is NoSQL with schemaless collections with ability to store various JSON documents types and because of that you'll need to get schema per document type.
While using fullstack javascript approach you can put your model in js module and use it on both front and backend.
for us, most reliable and scalable approach is based on Typescript as master with following-ish workflow
turn JSON to TS via VS Code extension json2ts.com
then you can
generate JSON Schema via typescript-json-schema
generate UML diagram with tsviz
convert JSON Schema to joi with enjoi
generate forms from JSON schema (front-end framework specific)

Can we retrive data of two tables in nodejs with mongoose [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I am working one project there is some relational concept so i want to retrieve data from two different tables in same query , can i do this ? i am following below link but i am not getting exact that i wants.
Mongoose/mongoDB query joins.. but I come from a sql background
I have also review this links
https://start.jcolemorrison.com/mongodb-joins-with-mongoosejs/
I have review this mongoose links, here i am getting something positive.
http://mongoosejs.com/docs/populate.html
What i have done so far is like below:
Create Models for project and project_category and try to get all project with category details. I have update my code at below link to review :
https://www.protectedtext.com/rushabhcode
mongooses have populate in built function to join two table
in schema just add ref for linking table
suppose you want to join two table
table 1 :User
table 2 :posts
in posts schema add
posted_by: {type: Schema.Types.ObjectId, ref: 'User', required: true},
and the time of query just add populate
suppose
postModel.find({}).populate({path:'posted_by'}).exec(function(err,response){
})
this will help you get all post value with user details who has posted

How to use one relational(postGreSql) and one non-relational(MongoDb) database in single node.js application

I have to work on one Node Js project where I have to use two database in single application, One database is MongoDb and the other one is postgreSql. Till now I have only used only one dababase in one project. I just want to know that "Is it possible to use two different database as mentioned above in one Node Js project". If yes can you please provide me essential configs and plugin required to setup the project ?
yeah... NoSQL & another RDBMS together...because
NoSQL: fast and simple, but has little to none structure to enforce constraints on data.
RDBMS: satisfies all ACID properties, keeping your data safe and clean. But performance goes down rapidly as traffic and data set size grow.
for doing so ..
you can use an ODM (Object Document Mapper) like mongoose to deal with mongoDB
& an ORM (Object Relational Mapper) like sequalize to deal with mysql , postgre
As provided in the docs.. you got to install both
npm i -s mongoose sequelize

MongoDB create a new collection from the client side?

Intro:
I have a collection of players in my app, this is built using a schema and then passing some stuff into my node.js configuration, perhaps it's a bit more complex than that but I mean this is the basic idea of how mongoDB for nodejs works with models and collections.
So now in my database I have my DB name then collections then a collection of players, great now I can build an api and start making requests to GET and PUT from that collection.
Question:
My problem is in my stats app after week one's game was tracked I need to clear all the player attributes so that in week 2 it's fresh, but I would like to save all the stats for the players from week 1.
So due to my basic knowledge of how a collection is built I am thinking in order to build a new collection I need to define a schema, but perhaps there is another way, if not then the schema would have to be dynamic right? Well how do I build a dynamic schema to suit this problem?
Ideas:
Idea: The user clicks a button saying complete week 1, then the server takes all the data from the players collection and builds a
new collection named week 1 players?
Question: If the above is a good idea, how do I build a function to create a new mongoDB collection and save players_week1 into its
own branch?
Final Word:
So hopefully someone has an optimal solution and understands what I am talking about, in the mean time I am going to try and follow my idea and see if I can search the docs to find some answers. Thanks guys.

Categories