Nodejs Mongodb – Document Property is ‘Undefined ‘ when printing

I’m learning Node, Express & Mongodb, hence a very much beginner. I’m developing a form where in there is a text field in which user will add data.

First, i need to check if that data exist or not in a master table. If exist, then i will return the record id else i will create a new record and return its id. Below is the code which I had tried but it’s giving me id as undefined.

code.js (controller)

const toolsModel = require('../models/modTools');
const { validationResult } = require('express-validator');
module.exports = {
        async saveCode(req, res)
        {
            var promiseToolId = () => {
            return new Promise((resolve, reject) => {
            let tool_exist = toolsModel.findOne({ title: req.body.inpTool });

            if (tool_exist) {
                console.log('tool_exist'); // prints this line
                console.log(tool_exist._id); // gives undefined
                console.log(tool_exist); // prints the object.
                resolve(tool_exist._id);
            }
            else{
                console.log('tool not exist. inserting');
                var newTool = new toolsModel();
                newTool.insert({title: req.body.inpTool, created_at: new Date()}, function(err, newRec)              {
                if(err){
                    console.log('err while inserting');
                    console.log(err);
                    reject(err);
                }
                else{
                    console.log('inserted');
                    console.log(newRec);
                    resolve(newRec._id);
                }
                });
            }
            });
        };

        let errors = validationResult(req);
        if (!errors.isEmpty()){
            console.log('validation error');
            console.log(errors);
        }
        else{
            console.log('form is valid'); // prints this line

            // check if the tool exists in our database
            var toolId = await (promiseToolId()); //anything here is executed after result is resolved 
            console.log('toolId ', toolId); // prints undefined
        }
        }
};

modTools.js (model)

const mongoose = require('mongoose'),
    timeZone = require('mongoose-timezone'),
    Schema = mongoose.Schema;

const toolsSchema = new Schema({
    title: {type:String, required:true, trim: true},
    created_at: {type: Date, default: Date.now},
});

toolsSchema.plugin(timeZone);

module.exports = mongoose.model('developmentTools', toolsSchema);

Please note that I’m using Auto-increment id for my model above which i had created using below codes.

db.createCollection("developmentTools");

db.developmentTools.insert ( {_id: "toolsId" , toolSeqValue : 0 } );


function getToolsNextID(seqName) {
  var seqDoc = db.developmentTools.findAndModify({
    query: { _id: seqName },
    update: { $inc: { toolSeqValue: 1 } },
    new: true
  });
  return seqDoc.toolSeqValue;
}

I know the way I’m accessing the object property tool_exist.title is correct but dont know why its giving me undefined.

M I wrong in implemenation of the Promise?

Please help.

Much Regards,

Javed Ansari

Answer

I’m able to resolve the issue. Listing the complete code if anyone faces the same issue. Thanks a lot to @ifaruki for sharing the informative URL and @slimane-amiar for his time.

async saveCode(req, res)
    {
        async function createTool(tool_ttle){            
            var newTool = new toolsModel({
                title: tool_ttle,
                created_at: new Date()
            });

            return new Promise((resolve, reject) => {                
                newTool.save((err, newRec) => {
                    if(err){
                        console.log('err while inserting');
                        reject(err);
                    }
                    else{
                        console.log('inserted');
                        resolve(newRec);
                    }
                });                
            });
        }

        let errors = validationResult(req);
        if (!errors.isEmpty()){
            console.log('validation error');
            console.log(errors);
        }
        else{
            console.log('form is valid');
            
            toolTitle = req.body.inpTool;
            toolTitle = toolTitle.trim().toUpperCase();
            let toolRecord = '';

            // check if the tool exists in our database
            try {
                toolRecord = await toolsModel.findOne({ title: toolTitle });
                if (toolRecord){
                    console.log('tool_exist');
                    console.log(toolRecord);
                }
                else{
                    console.log('tool not exist. inserting');
                    toolRecord = await createTool(toolTitle);
                    if(toolRecord){
                        console.log('new tool is created below');
                        console.log(toolRecord);
                    }
                    else
                    {
                        console.log('error in creating new tool');
                        console.log(toolRecord);
                    }
                }
            }
            catch(error){
                console.log('in catch');
                console.log(error);
                return error;
            }

            console.log('proceeding further');            
        }
    }

Leave a Reply

Your email address will not be published. Required fields are marked *