mongoose check if document exists

Solutions on MaxInterview for mongoose check if document exists by the best coders in the world

showing results for - "mongoose check if document exists"
Laura
24 May 2020
1var query = Model.find({
2    /* query */
3}).lean().limit(1);
4
5// Find the document
6query.exec(function(error, result) {
7    if (error) { throw error; }
8    // If the document doesn't exist
9    if (!result.length) {
10        // Create a new one
11        var model = new Model(); //use the defaults in the schema
12        model.save(function(error) {
13            if (error) { throw error; }
14            // do something with the document here
15        });
16    }
17    // If the document does exist
18    else {
19        // Update it
20        var query = { /* query */ },
21            update = {},
22            options = {};
23
24        Model.update(query, update, options, function(error) {
25            if (error) { throw error; }
26            // do the same something with the document here
27            // in this case, using result[0] from the topmost query
28        });
29    }
30});