Mongoose CRUD Operations

JS
S
JavaScript

Simple snippet that works also as cheatsheet demonstrating CRUD operations over mongoose models

1const methods = {
2    create: (req,res, next) => {
3        const entry = new Standup({
4            name: req.body.name,
5            project: req.body.project,
6            workYesterday: req.body.workYesterday,
7            workToday: req.body.workToday,
8            impediments:  req.body.impediments
9        });
10        // Save
11        entry.save((err)=>{
12            if(err){
13                res.render('newnote', {title: 'New note error', error: err});
14            } else {
15                res.redirect(301,'/');
16            }
17        });
18    },
19    list: (req,res,next) => {
20        const query =  Standup.find();
21        query.sort({'createdOn': 'desc'})
22            .exec((err,data) => {
23                res.render('index', {title: 'List of notes', notes: data})
24            });
25    },
26    get: (req,res,next) => {
27        // get all elements
28
29        res.render('newnote', {title: 'New note page'});
30
31        const deferredQuery = Standup.find();
32        deferredQuery.exec((err,data)=>{
33            // console.log(data);
34        });
35
36        const immediateQuery = Standup.find((error, data) => {
37            // console.log(data);
38        });
39
40        const queryParams = Standup.find({name: 'Sample'}, (error,data)=> {
41            // console.log(data);
42        });
43
44        const queryParamsProjected = Standup.find({name: 'Adrian Murray'},'name project', (error,data)=> {
45            // console.log(data);
46        });
47
48        // ID
49        const id = '5a36e8bebaa42e16d029b497';
50        const findById = Standup.findById(id, '-impediments').exec((err,data) => {
51            // console.log(data);
52        });
53
54        // Query Operators
55        const opFind = Standup.find({workYesterday: {$gte:1, $lt:20}}, (err,data)=>{
56            // console.log('opFind',data);
57        });
58
59        const opWhere = Standup.where('workYesterday').gte(1).lt(2).exec((err, data) => {
60            if(err){
61                throw err;
62            }
63            // console.log('opWhere', data);
64        });
65
66        const chainedWhere = Standup
67            .where('workYesterday').gte(1).lt(2)
68            .where('impediments').ne('test')
69            .where('impediments', 'Quia iusto officia facere quis enim fugiat duis ad est adipisci eius dolorem ut error')
70            .exec((err,data)=>{
71                if(err){
72                    throw err;
73                }
74                console.log(data);
75            })
76
77        // Update and Remove
78        const updateWithQuery = Standup.findById(id, (err,doc)=>{
79            if(err){
80                return errorHandler(err);
81            }
82            doc.impediments = 'None';
83            doc.save((err, data) => {
84                if(err){
85                    return errorHandler(err);
86                }
87                console.log('Document Updated');
88            });
89        });
90
91        // Update directly
92        const uOptions = {
93            safe: true, // default to value set in schema
94            upsert: false, // create a new doc if condition not found
95            multi: false, // update multiple docs at the same time
96            strict: false, //
97            overwrite: false //disable update only mode
98        }
99        const uCondition = { name: 'Adrian Murray' };
100        const uUpdate = { impediments: 'None' };
101        const update = Standup.update(uCondition, uUpdate, uOptions, (err,data)=> {
102            if(err){
103                return errorHandler(err);
104            }
105            // console.log('Document updated');
106        });
107
108        // Find One and Update
109        const findOneAndUpdate = Standup.findOneAndUpdate(uCondition, uUpdate,(err,data)=>{
110            if(err){
111                return errorHandler(err);
112            }
113            console.log('Document updated',data);
114        });
115
116        // Remove
117        const date = new Date(2018,12,01);
118        const rCondition = { createdOn: { $gte: date }};
119        const remove = Standup.remove(rCondition, (err) => {
120            if(err){
121                return errorHandler(err);
122            }
123            console.log('Document removed');
124        });
125
126
127
128        // By id and Updte
129        const fbidOptions = {
130            new: true, // return the new modified document
131            upsert: false, // create a new doc if not found
132            select: true // specify projection to be returned
133        }
134        const fbidUpdate = { impediments: 'Blocker' };
135        const findByIdAndUpdate = Standup.findByIdAndUpdate(id, fbidUpdate, (err, data)=>{
136            if(err){
137                return errorHandler(err);
138            }
139            console.log('findByIdAndUpdate',data);
140        });
141
142        // By Id and Remove
143        const fbirOptions = {
144            select: true // specify projection to be returned
145        }
146        const removeCondition = { impediments: 'Blocker' };
147        const findByIdAndRemove = Standup.findByIdAndRemove(id, removeCondition, fbirOptions, (err, data)=>{
148            if(err){
149                return errorHandler(err);
150            }
151            console.log('findByIdAndRemove',data);
152        });
153    },
154    filterBy: (req,res,next) => {
155        const filterName = req.body.filterByName;
156        const query = Standup.find();
157        debugger;
158        if (filterName && filterName.length > 0){
159            query.where({name: filterName})
160        }
161        query.exec((err,results)=>{
162            res.render('index', {title: 'List of notes', notes: results});
163        });
164    }
165};
166const errorHandler = (err => {
167    throw new err;
168});

Created on 2/27/2019