Mongoose CRUD
CRUD Setup
// grab the user model
var User = require('./app/models/user');
// create a new user
var newUser = User({
name: 'Hemant',
age: 30
});
Create create a new user
// save the user
newUser.save(function(err) {
if (err) throw err;
console.log('User created!');
});
Read
one specific user
all users
similar users
Find All get all the users
// Model.find(conditions, [fields], [options], [callback])
User.find({}, function(err, users) {
if (err) throw err;
console.log(users);
});
// No callback...
// Deferred execution
var query = User.find();
// With callback... Executes query immediately
User.find(function (err, results) {
// handle the error... Or results here
});
// With callback and query conditions
User.find({ memberName: 'Hemant' }, function (err, results) {
// handle the error... Or results here
});
// Limit the returned fields...
User.find({ memberName: 'Hemant' }, 'name, age', function (err, results) {
// handle the error... Or results here
});
// Limit the returned fields with option
// Options examples... skip, limit, sort
User.find({ memberName: 'Hemant' }, 'name, age', { limit: 10 }, function (err, results) {
// handle the error... Or results here
});
Find One
// No callback... No conditions...
var query = User.findOne();
query.exec(function (err, results) {
// handle the error... Or results here
});
// With conditions...
var query = User.findOne({ memberName: ‘Mark’});
// With condition, no field filtering, and options...
var query = User.findOne({ memberName: 'Hemant'}, null, { limit: 10 });
Find By ID
// get a user with ID of 1
User.findById(1, function(err, user) {
if (err) throw err;
console.log(user);
});
Querying
// get the date 1 month ago
var monthAgo = new Date();
monthAgo.setMonth(monthAgo.getMonth() - 1);
User.find({ admin: true }).where('created_at').gt(monthAgo).exec(function(err, users) {
if (err) throw err;
// show the admins in the past month
console.log(users);
});
// Model.where(path, [val])
Customer.find({ discount: {$gte: 10, $lt: 20}, function(err, results) {
if (err) throw err;
console.log(results);
});
Customer.where(‘discount’).gte(10).lt(20).exec(function(err, results) {
if (err) throw err;
console.log(results);
});
// Chain where methods together...
Customer.where(‘discount’).gte(10).lt(20)
.where(‘zipCode’, ‘12345’)
.exec(function(err, results) {
if (err) throw err;
console.log(results);
});
Querying Operator
$gt greater than
$gte greater than or equal to
$in exists in
$lt less than
$lte less than or equal to
$ne not equal to
$nin does not exist
Update
// Model.update(conditions, update, [options], [callback])
// Example: update multiple documents that match condition
var condition = { firstName: ‘Bob’ };
var update = { firstName: ‘Robert’ };
Customer.update(condition, update, { multi: true }, function(err, numberAffected, raw) {
// Handle error, returned # affected, and raw response from MongoDB...
});
Get a User, Then Update
User.findById(1, function(err, user) {
if (err) throw err;
user.location = 'uk';
user.save(function(err) {
if (err) throw err;
console.log('User successfully updated!');
});
});
Find and Update
// find the user hemant
// update him to Varun
User.findOneAndUpdate({ username: 'hemant' }, { username: 'Varun' }, function(err, user) {
if (err) throw err;
console.log(user);
});
Find By ID and Update
// find the user with id 4
// update username to Hemant
User.findByIdAndUpdate(4, { username: 'Hemant' }, function(err, user) {
if (err) throw err;
console.log(user);
});
Delete
Get a User, Then Remove
User.find({ username: 'hemant' }, function(err, user) {
if (err) throw err;
user.remove(function(err) {
if (err) throw err;
console.log('User successfully deleted!');
});
});
Find and Remove
// find the user with id 4
User.findOneAndRemove({ username: 'hemant' }, function(err) {
if (err) throw err;
console.log('User deleted!');
});
Find By ID and Remove
// find the user with id 4
User.findByIdAndRemove(4, function(err) {
if (err) throw err;
console.log('User deleted!');
});
Last updated
Was this helpful?