# Mongoose CRUD

## CRUD Setup

```javascript
// 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

```javascript
// 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

```javascript
// 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

```javascript
// 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

```javascript
// get a user with ID of 1
User.findById(1, function(err, user) {
  if (err) throw err;

  console.log(user);
});
```

### Querying

```javascript
// 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

```javascript
// 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

```javascript
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

```javascript
// 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

```javascript
// 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

```javascript
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

```javascript
// 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

```javascript
// find the user with id 4
User.findByIdAndRemove(4, function(err) {
  if (err) throw err;

  console.log('User deleted!');
});
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://hemantajax-2.gitbook.io/mongoose-step-by-step/mongoose-crud.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
