如何在节点js中检查文本框ID是否为null

时间:2019-08-21 17:00:21

标签: javascript node.js mongodb

我在我的nodejs mongodb数据库连接程序中遇到长度错误

我尝试用mongodb指南针

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var urlEncodedParser = bodyParser.urlencoded({extended:false});
const {ObjectId} = require('mongodb');
app.use(express.static('public'));
app.engine('html',require('ejs').renderFile);
app.set('view engine','html');
app.set('views',__dirname);

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/productDB";

app.post('/submitData',urlEncodedParser,function(req,res){
    var id = req.body.id;
    var productCode = req.body.txtCode;
    var productName = req.body.txtName;
    var price = req.body.txtPrice;
    var taxable = req.body.radioTax;

    console.log("length:%d",id.length);

    if(id.length > 0)
    {
        MongoClient.connect(url,function(err,db){
            if(err)
                throw err;
             var qry = {productCode:productCode};
             var data = {$set:{productName:productName,price:price,taxable:taxable}};
             db.collection("tblProduct").updateOne(qry,data,function(err,res){
                if(err)
                    throw err;
                console.log("Updated");
                db.close();
             });
        });
    }
    else
    {
        MongoClient.connect(url,function(err,db){
            if(err)
                throw err;
            db.collection('tblProduct').insertOne({
                productCode:productCode,
                productName:productName,
                price:price,
                taxable:taxable
            });
            console.log("Inserted");
        });
    }
    res.redirect("/showProduct");
});

我希望将结果作为ID的长度。我想要长度错误的解决方案,也想检查我的文本框是否为空。如果为null,则将插入新记录;如果不为null,则将更新现有记录。

1 个答案:

答案 0 :(得分:0)

if(typeof id != 'undefined')
    {
        MongoClient.connect(url,function(err,db){
            if(err)
                throw err;
             var qry = {productCode:productCode};
             var data = {$set:{productName:productName,price:price,taxable:taxable}};
             db.collection("tblProduct").updateOne(qry,data,function(err,res){
                if(err)
                    throw err;
                console.log("Updated");
                db.close();
             });
        });
    }