node express mongodb将数据添加到数据库中

时间:2017-05-31 15:00:44

标签: node.js mongodb express

如果我的数据库中不存在该词,我需要向数据库添加单词,如果存在则显示消息“word arleady exists,输入另一个单词”。现在我的代码添加新单词或更新如果单词存在,但我不能做警告消息,以显示该单词arleady存在

router.post('/insert', function (req, res, next) {
    if (req.body.title.length == 0) {
        var inputFile = "./k5audios/" + req.body.inputFile;
        var item = {
            title: req.body.inputFile.substring(0, (req.body.inputFile.length - 4)),
            content: inputFile
        }
    } else {
        var item = {
            title: req.body.title.toLowerCase(),
            content: "https://ssl.gstatic.com/dictionary/static/sounds/de/0/" + req.body.title.toLowerCase() + ".mp3"
        }
    }

    mongo.connect(url, function (err, db) {
        assert.equal(null, err);
       db.collection('words').update(item,
           {$inc: {score: 1}},
           {upsert: true, safe: false},
           function(err,data){
               if (err){
                   console.log(err);
               }else{
                   console.log("score succeded");
               }
           });
    });
});
<form action="/insert" method="post">
                                <div class="modal-body">
                                    <div class="form-group">
                                        <label for="title">New Word</label>
                                        <input type="text" class="form-control" id="title" name="title" placeholder="Enter new word">
                                    </div>
                                    <div class="form-group">
                                        <label for="exampleInputFile">File input</label>
                                        <input type="file" id="inputFile" name="inputFile">
                                    </div>
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                                    <button type="submit" class="btn btn-primary">Save changes</button>

                                </div>

                            </form>

enter image description here

0 个答案:

没有答案