search

Home  >  Q&A  >  body text

Mongodb queries whether a piece of data exists?

Suppose I have name=1,name=2 in my database

If you use name=2 to query. When name=2 exists, output the data related to that

Now I use name=3 to query. Add name=3

when name=3 does not exist

How to write using if judgment. .

高洛峰高洛峰2833 days ago621

reply all(1)I'll reply

  • 给我你的怀抱

    给我你的怀抱2017-05-02 09:25:23

    function add(data,col){
    MongoClient.connect(Url, function (err, db) {
            var collection = db.collection(col);
            collection.findOne({'name':data},function(err, doc) {
                if(doc) {
                    console.log(doc);
                    db.close();
                } else {
                    collection.insertOne({'name':data},function () {
                    db.close();
                    });
                }
            });
        });
        }

    reply
    0
  • Cancelreply