Definitely not comprehensive. This is meant to be a basic memory aid with links to get more details. I'll add to it over time.
$ npm install mongoose --save
const mongoose = require('mongoose');
const connectionString = process.env.MONGO_URI || 'mongodb://localhost/databasenamegoeshere';
//overwrite deprecated Mongoose promise
mongoose.Promise = global.Promise;
//connect to mongodb
mongoose.connect(connectionString, {useMongoClient: true})
.then(() => {
console.log('Connected to database at ', new Date().toLocaleString());
})
.catch((err) => {
console.error('Error connecting to the database: ', err);
});
const userSchema = new mongoose.Schema({
name: {
first: String,
last: { type: String, trim: true }
},
age: { type: Number, min: 0 },
posts: [ { title: String, url: String, date: Date } ],
updated: { type: Date, default: Date.now }
});
- String
- Number
- Date
- Buffer
- Boolean
- Mixed
- ObjectId
- Array
SchemaTypes
SchemaType API
SchemaType#default
SchemaType#validate
get
set
select
Mixed types and dates that are modified using JavaScript Date methods are not hooked into mongoose change tracking logic. To save changes, let mongoose know about them using markModified('path')
before calling save
.
A model is a constructor compiled from a schema. Model instances represent documents.
const User = mongoose.model('User', userSchema);
var u = new User({
name: {
first: 'Tony',
last: 'Pujals'
},
age: 99
});
The easiest way to query is to use Model.find, Model.findById, or Model.findOne methods.
These methods return a Query, which is not ideal. If you use the .exec()
method one of the above, you get a Promise.
To update something, use a Promise chain and work on the result. The following code changes the name on one object with the name of 'Bob' to 'Sam':
MyModel.findOne({name: 'Bob'}).exec()
.then(function(data){
data.name = 'Sam';
return data.save(); //we need the return because .save() returns a Promise & we're in a 'then' already
})
.then(function() {
//at this point the save is successful; we'd go to the catch otherwise
res.status(204); //use Express to send a response code
})
.catch(function(err) {
console.error(err);
res.status(400).json(err); //use Express to send a response code
});
You can also search on embedded documents: assuming you have a House where:
var HouseSchema = new mongoose.Schema({
address: AddressSchema
});
var House = mongoose.model('House', HouseSchema);
House.findOne({'address.city': 'Tuscaloosa'}).exec();
Assuming that the AddresseSchema has a field called 'city', 'address.city'
looks for a House document where House.address.city is Tuscaloosa.
You can use .select
to include and exclude fields: the following code selects the content, id, createdAt, and updatedAt fields and explicitly excludes the _id field by prefixing the field name with '-'. _id is automatically included by default unless explicitly excluded.
Joke.find().select('content id createdAt updatedAt -_id').exec()
.then(function(data) {
res.status(200).json(data);
})
.catch(function(err) {
console.error(err);
res.status(400).json(err);
});
You could also use Joke.find().select('-_id -__v').exec()
, which excludes the _id and __v fields and returns all other fields.
Queries overview Read this first
query.$where('this.comments.length > 10 || this.name.length > 5')
// or
query.$where(function() {
return this.comments.length > 10 || this.name.length > 5;
});
http://mongoosejs.com/docs/api.html#query_Query-count
http://mongoosejs.com/docs/api.html#query_Query-distinct
http://mongoosejs.com/docs/api.html#query_Query-elemMatch
http://mongoosejs.com/docs/api.html#query_Query-equals
http://mongoosejs.com/docs/api.html#query_Query-exec
http://mongoosejs.com/docs/api.html#query_Query-exists
http://mongoosejs.com/docs/api.html#query_Query-find
Finds a single document by its _id field. findById(id) is almost equivalent to findOne({ _id: id }). If you want to query by a document's _id, use findById() instead of findOne().
http://mongoosejs.com/docs/api.html#model_Model.findById
http://mongoosejs.com/docs/api.html#model_Model.findByIdAndRemove
http://mongoosejs.com/docs/api.html#model_Model.findByIdAndUpdate
When executed, the first found document is passed to the callback.
http://mongoosejs.com/docs/api.html#query_Query-findOne
http://mongoosejs.com/docs/api.html#query_Query-findOneAndRemove
http://mongoosejs.com/docs/api.html#query_Query-findOneAndUpdate
http://mongoosejs.com/docs/api.html#query_Query-gt
http://mongoosejs.com/docs/api.html#query_Query-gte
http://mongoosejs.com/docs/api.html#query_Query-hint
http://mongoosejs.com/docs/api.html#query_Query-in
http://mongoosejs.com/docs/api.html#query_Query-lean
http://mongoosejs.com/docs/api.html#query_Query-limit
http://mongoosejs.com/docs/api.html#query_Query-lt
http://mongoosejs.com/docs/api.html#query_Query-lte
http://mongoosejs.com/docs/api.html#query_Query-maxScan
http://mongoosejs.com/docs/api.html#query_Query-merge
http://mongoosejs.com/docs/api.html#query_Query-mod
http://mongoosejs.com/docs/api.html#query_Query-ne
http://mongoosejs.com/docs/api.html#query_Query-nin
http://mongoosejs.com/docs/api.html#query_Query-nor
http://mongoosejs.com/docs/api.html#query_Query-or
http://mongoosejs.com/docs/api.html#query_Query-populate
http://mongoosejs.com/docs/api.html#query_Query-read
http://mongoosejs.com/docs/api.html#query_Query-regex
- Removes all documents matching a query from a collection.
Ex.:
Album.remove({ artist: 'Anne Murray' }, callback);
- To remove all documents in a collection (sort of like drop collection, except the collection exists afterwards):
Album.remove({}, callback);
?? this one ??
http://mongoosejs.com/docs/api.html#model_Model-collection
?? or this one ??
http://mongoosejs.com/docs/api.html#query_Query-remove
Saves this document. Returns a Promise.
http://mongoosejs.com/docs/api.html#model_Model-save
http://mongoosejs.com/docs/api.html#query_Query-select
http://mongoosejs.com/docs/api.html#query_Query-setOptions
http://mongoosejs.com/docs/api.html#query_Query-size
http://mongoosejs.com/docs/api.html#query_Query-skip
http://mongoosejs.com/docs/api.html#query_Query-slice
http://mongoosejs.com/docs/api.html#query_Query-snapshot
http://mongoosejs.com/docs/api.html#query_Query-sort
http://mongoosejs.com/docs/api.html#query_Query-stream
http://mongoosejs.com/docs/api.html#query_Query-tailable
http://mongoosejs.com/docs/api.html#query_Query-toConstructor
http://mongoosejs.com/docs/api.html#model_Model.update