Creating a collection schema in a mongolab mongodb database from node.js

I am new to node.js and mongodb ... help.

I am trying to create a schema for a collection of users in a mongolab mongodb database from a node.js application with the code below. The code doesn't seem to work (at least I don't get error messages), but I see no signs that it is succeeding. That is, when I go to the Mongolab and look at my database, I don’t see any scheme being created - http://cl.ly/image/0f1y273m2i0X .

Can someone explain what I can do wrong, or how can I verify that my code has succeeded and actually created a circuit for my collection?

---- BEGIN CODE ----

// file: app.js var express = require('express'), http = require('http'), mongoose = require('mongoose'); var app = express(), port = 3000; // Connect to database in the cloud (mongolab) mongoose.connect('mongodb://username: password@ds041344.mongolab.com :41344/stockmarket'); // Create a schema for User collection mongoose.connection.on('open', function () { console.log(">>> Connected!"); var UserSchema = new mongoose.Schema({ username: {type: String, unique: true}, password: String }); var UserModel = mongoose.model('User', UserSchema); }); app.get('/', function(req, res){ res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello, World!\n'); }); http.createServer(app).listen(port, function(){ console.log("Express server listening on port " + port + " ..."); }); 

---- END CODE ----

+7
source share
2 answers

You must insert the document first. Schemas are not defined explicitly in mongodb. After you enter the document, the collection will be automatically created and you will see it in the mongolab console.

Example from http://mongoosejs.com/

 var mongoose = require('mongoose'); var db = mongoose.createConnection('localhost', 'test'); var schema = mongoose.Schema({ name: 'string' }); var Cat = db.model('Cat', schema); var kitty = new Cat({ name: 'Zildjian' }); kitty.save(function (err) { if (err) // ... console.log('meow'); }); 

after calling save over collection will be created

+8
source

Data in MongoDB has a flexible scheme. Documents in the same collection do not have to have the same set of fields or structures, and common fields in collection documents can contain different types of data.

0
source

All Articles