Reputation: 329
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 }
});
Upvotes: 0
Views: 191
Reputation: 179
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()
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. http://mongoosejs.com/docs/guide.html.
Upvotes: 1