[Mongoose snippets] Tips for mongoose #mongoose
userSchema.pre("save", function() {
if (!this.createdOn) {
this.createdOn = new Date().toString();
this.modifiedOn = new Date().toString();
} else {
this.modifiedOn = new Date().toString();
}
});
// Aggregation/populate setup:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const personSchema = Schema({
_id: Schema.Types.ObjectId,
name: String,
age: Number,
stories: [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});
const storySchema = Schema({
author: { type: Schema.Types.ObjectId, ref: 'Person' },
title: String,
fans: [{ type: Schema.Types.ObjectId, ref: 'Person' }]
});
const Story = mongoose.model('Story', storySchema);
const Person = mongoose.model('Person', personSchema);
// Population:
// return everything
await Story.
findOne({ title: 'Casino Royale' }).
populate('author')
// return only name
Story.
findOne({ title: /casino royale/i }).
populate('author', 'name'). // only return the Persons name
// populate multiple paths:
Story.
find(...).
populate('fans').
populate('author')
// other options
Story.
find(...).
populate({
path: 'fans',
match: { age: { $gte: 21 }},
// Explicitly exclude `_id`, see http://bit.ly/2aEfTdB
select: 'name -_id',
options: { limit: 5 }
}).
var Person = mongoose.model('Person', yourSchema);
// find each person with a last name matching 'Ghost', selecting the `name` and `occupation` fields
Person.findOne({ 'name.last': 'Ghost' }, 'name occupation', function (err, person) {
if (err) return handleError(err);
// Prints "Space Ghost is a talk show host".
console.log('%s %s is a %s.', person.name.first, person.name.last,
person.occupation);
});
// multi query:
Person.
find({
occupation: /host/,
'name.last': 'Ghost',
age: { $gt: 17, $lt: 66 },
likes: { $in: ['vaporizing', 'talking'] }
}).
limit(10).
sort({ occupation: -1 }).
select({ name: 1, occupation: 1 }).
exec(callback);
// only get 'name' and 'occupatiton'
Person.findOne({ 'name.last': 'Ghost' }, 'name occupation');