Genjik Genjik - 3 years ago 172
Node.js Question

Data modeling in mongoose

I'm creating my website with node.js(express.js) and I have one question about mongodb and mongoose.
This question is how to make schema for my collection? For example I have users on my webiste, and user can subscribe for another user? How to write schema for this?
For now I have something like this:

userSchema = mongoose.Schema({
username: { type: String, required: true, unique: true },
password: { type: String, required: true }

Answer Source

This line will allow you to add things to the database via the schema. (Very idiomatically, the database will be called 'users', as Mongoose pluralises the first argument for you.)

mongoose.model('user', userSchema);

There are a couple of ways to add things to the database - I use promises, which requires you to call this before you connect (I think it has to be before?)

mongoose.Promise = Promise;

You can then save new instances of the schema:

new User ({
  username: 'me',
  password: 'dontlooknow',

Save returns a promise, so you can follow it with a .then() after if you want. You can do it with callbacks too if you prefer, just look at the docs.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download