Anna K
Anna K

Reputation: 1774

MongoDB update if user not exists

I have a problem to update user if his/her name is not available in my database

I thought if my function "User.findOne" doesn't find a user in my mongodb it can update database. Unfortunately nothing happens. I get only output "Hello Anna you are new here!" My name is not saved into my mongodb

Could somebody smart give me please a tip how can I save username if it is not in my database

var User = require('./user');
var myName = this.event.request.intent.slots.first_name.value;
self = this;

User.findOne({ name: myName }, function(err, user) {
    if (err ||!user){
        var userSave = new User({
            name: myName
        });

        userSave.save(function (err, results) {
            console.log(results);
            self.emit(':ask',
                "Hello "+ myName +"you are new here!")
        });

    }
    else {
        self.emit(':ask',
            "Hello "+ myName +" you are not new!")
    }

});

My mongoose model code:

//user.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

mongoose.connect("mongodb://c******mlab.com:***/users");

var userSchema = new Schema({
    name: String,
    userId: { type: String, required: false, unique: true }
});

var User = mongoose.model('User', userSchema);


module.exports = User;

Upvotes: 0

Views: 735

Answers (2)

kevinadi
kevinadi

Reputation: 13785

The line if (err || !user) is confusing to read, and in this style you're mixing error handling (if (err)) and a condition in your code that you expect to hit (if (!user)). I suggest you separate them so the code is easier to read and debug.

For example, using plain Javascript and the MongoDB node driver:

var MongoClient = require('mongodb').MongoClient;

MongoClient.connect('mongodb://localhost/test', function(err, conn) {

    // connection error handling
    if (err) {
        console.log('Connection error: ' + err);
    }
    conn.db('test').collection('test').findOne({name:'abc'}, function(err, doc) {
        // findOne error handling
        if (err) {
            console.log('Error: ' + err);
        }

        // if document exists
        if (doc) {
            console.log('Document found: ' + JSON.stringify(doc));
        }

        // if document doesn't exist
        else {
            console.log('Document not found');
        }
        conn.close();
    });
});

If the database contains the user abc, the output would be:

$ node script.js
Document not found

If the user abc exists:

$ node script.js
Document found: {"_id":0,"name":"abc"}

I believe using a similar pattern you can modify your code to do what you need.

Upvotes: 0

unm4sk
unm4sk

Reputation: 345

var User = require('./user');
var myName = this.event.request.intent.slots.first_name.value;
self = this;

User.findOne({
  name: myName
}, (err, user) => {
  if(err) throw err;
  if(user) {
    self.emit(':ask', `Hello ${myName} you are not new`);
  } else {
    User.create({
      name: myName
    }, (err, result) => {
      if(err) throw err;
      console.log(result);
      self.emit(':ask', `Hello ${myName} you are new here!`);
    })
  }
});

this should work.

Upvotes: 1

Related Questions