【问题标题】:How to use mongoose or mongodb to check for repeated data (Node.js + Express)如何使用 mongoose 或 mongodb 检查重复数据(Node.js + Express)
【发布时间】:2017-05-13 00:06:47
【问题描述】:

我想知道是否有一种方法可以在使用 mongodb 和 mongoose 将它们输入数据库之前检查重复值。我基本上是在寻找一种验证数据的方法,即数据不会重复,因此我不会浪费空间。我希望有人能指出我正确的方向或向我展示解决方案,谢谢。

App.js:

    var print = require('./print');
var express = require("express");
var app = express();

var bodyParser = require('body-parser');
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var config = require('./config.js');

app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'ejs');
app.get('/', function(req, res) {
    res.render("post");
    print("All is in order");
})

app.listen(config.port, function() {
   print(`listening on ${config.port}`);
})

MongoClient.connect(config.localUrl, function(err, db) {
    if(err) {
      console.log('Unable to connect to the mongoDB server. Error:', err);
      return;
    }
    var collection = db.collection('users');
    app.post('/post', function(req, res) {

      var name = req.body.name
      var email = req.body.email
      res.send(`You sent the name ${name} and the email ${email}`);
      var user1 = {};
      user1.name = name;
      user1.email = email;
      //validate no repeated values
      collection.insert(user1, function(err,result){
        if (err) {
          console.log(err);
        } else {
          console.log('The Results', result);
          db.close();
        }
      })
    })

  })

【问题讨论】:

    标签: node.js mongodb express web-applications mongoose


    【解决方案1】:

    【讨论】:

    • 怎么回事,唯一的例子只使用更新功能(对不起,这可能是一个愚蠢的问题,但我是 mongodb 的新手)。
    • 如果查询返回null,您也可以从节点ad进行查询,这意味着您没有存储文档。现在,您可以插入新文档了。
    猜你喜欢
    • 1970-01-01
    • 2011-12-07
    • 2011-12-07
    • 2016-05-01
    • 1970-01-01
    • 2019-06-14
    • 1970-01-01
    • 2021-07-10
    • 1970-01-01
    相关资源
    最近更新 更多