0

I've been through the docs, tutorials and SO. I just can't seem to find the right answer on how to properly update an entry that's already in the database.

I can insert data just fine but the second I try to update it using the below query, it fails. It's wrong in some way but I can't figure it out. I copied from the docs, tuts, etc. Still no go.

My insert works fine so it can't be a connection issue.

This is my update code

db.collection("usercollection").findOne({ 'playerName': sPlayerName, 'playerId': sPlayerID})

db.collection("usercollection").update({ 'playerName': sPlayerName },{$set: { 'playerScore': sPlayerScore}});

I'm trying to update the "playerScore" field using $set.

From what I understand, I have to "findOne" entry first then update it. I just keep getting "TypeError: object is not a function" error message when I run the update code in my Node.JS app.

Here's my whole function:

    function insertEntry(sPlayerName, sPlayerID, sPlayerScore, sPlayerHealth) 
{
        var Db = require('mongodb').Db,
        MongoClient = require('mongodb').MongoClient,
        Server = require('mongodb').Server,
        ReplSetServers = require('mongodb').ReplSetServers,
        ObjectID = require('mongodb').ObjectID,
        Binary = require('mongodb').Binary,
        GridStore = require('mongodb').GridStore,
        Grid = require('mongodb').Grid,
        Code = require('mongodb').Code,
        BSON = require('mongodb').pure().BSON,
        assert = require('assert');

        var db = new Db('mdata', new Server('localhost', 27017));
            db.open(function(err, db) {
                if(!err) {
                // Fetch a collection to insert document into
        var collection = db.collection("usercollection"); 

        if(sPlayerScore < 101) {
            db.collection("usercollection").insert({ 'playerName': sPlayerName, 'playerId': sPlayerID, 'playerScore': sPlayerScore}, { w: 0 }); }

        else if(sPlayerScore > 190) {
            db.collection("usercollection").findOne({ 'playerName': sPlayerName, 'playerId': sPlayerID})
            db.collection("usercollection").update({ 'playerName': sPlayerName },{$set: { 'playerScore': sPlayerScore}});
            }
        }
   });
}

I know this isn't exactly ActiveRecord or anything, but I thought I could "findByAttributes" in a similar way with MongoDB.

edit:

I updated my queries with error callbacks. Now whenever there is an error, I get this in console:

C:\xampp\htdocs\projectapp\node_modules\mongodb\lib\mongodb\connection\base.js:246
        throw message;
              ^
TypeError: object is not a function
    at C:\xampp\htdocs\projectapp\node_modules\mongodb\lib\mongodb\collection\query.js:164:5
    at Cursor.nextObject (C:\xampp\htdocs\projectapp\node_modules\mongodb\lib\mongodb\cursor.js:753:5)
    at commandHandler (C:\xampp\htdocs\projectapp\node_modules\mongodb\lib\mongodb\cursor.js:727:14)
    at C:\xampp\htdocs\projectapp\node_modules\mongodb\lib\mongodb\db.js:1899:9
    at Server.Base._callHandler (C:\xampp\htdocs\projectapp\node_modules\mongodb\lib\mongodb\connection\base.js:453:41)
    at C:\xampp\htdocs\projectapp\node_modules\mongodb\lib\mongodb\connection\server.js:481:18
    at MongoReply.parseBody (C:\xampp\htdocs\projectapp\node_modules\mongodb\lib\mongodb\responses\mongo_reply.js:68:5)
    at null.<anonymous> (C:\xampp\htdocs\projectapp\node_modules\mongodb\lib\mongodb\connection\server.js:439:20)
    at emit (events.js:95:17)
    at null.<anonymous> (C:\xampp\htdocs\projectapp\node_modules\mongodb\lib\mongodb\connection\connection_pool.js:201:13)

Got this error message when using the findOne query only (I removed the update query for now, since I was getting no where)

if(sPlayerScore > 190) {
        db.collection("usercollection").findOne({'playerName': sPlayerName, 'playerId': sPlayerID}), function(err, result) {
            if(err)
                throw err;

            console.log("entry saved");
        }}; 
Entryton
  • 57
  • 1
  • 2
  • 9
  • Sorry I think I got it now. Had a problem with pasting it. – Entryton Dec 11 '14 at 06:48
  • Much better, thanks. You should be providing callback functions to your `insert` and `update` calls so you can catch any errors. What's the purpose of the `findOne` without a callback to get the result? – JohnnyHK Dec 11 '14 at 06:52
  • I added the callback function but my error message isn't really pointing to an area that I can fix. Seems like I got major code confusion going on - am I trying to do something that's not possible with Mongo or Node with this function ? Thanks again. – Entryton Dec 11 '14 at 19:40

1 Answers1

2

Your code is all over the place. This should be easily handled with a simple findOneAndUpdate, optionally with upsert if you want to create the player if they don't exist.

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

function insertEntry(sPlayerName, sPlayerID, sPlayerScore, sPlayerHealth)
{
  MongoClient.connect('mongodb://127.0.0.1:27017/mdata', function(err, db) {
    if(err) { throw err; }

    var userCollection = db.collection('usercollection');

    var player = {
      playerName: sPlayerName,
      playerId: sPlayerID,
      playerScore: sPlayerScore
    };

    var query = {
      playerName: sPlayerName,
      playerId: sPlayerID
    }

    var sort = {};

    var options = {
      upsert: true;
    }

    userCollection.findAndModify(query, sort, player, options, function(err, doc) {
      if(err) { throw err; }

      // player updated or inserted
    });
  }
}
Timothy Strimple
  • 22,920
  • 6
  • 69
  • 76
  • Timothy, first off I want to thank you very much. There was some minor syntax errors in your code but I was able to figure that out. (not complaining in the least), second, if you can explain to me why my code didn't work. I have a general understanding but if you could point at 1 or 2 major things I think it would really help me! (example - "Your code is all over the place. ") Thank you again !!!!!!!!!!!!!!!!! If I could upvote I would. – Entryton Dec 12 '14 at 15:43
  • I will say the big thing that confuses me - why did my insert query work and my update or findOne did not? That just doesn't make sense to me. Were my queries wrong for the update and find? – Entryton Dec 12 '14 at 15:54
  • There are a number of problems, but I'm not sure if they are from you pasting them into the question or if they are in the original source. If you put your entire file in a pastebin (minus and credentials if you have them in there), I will take a look and see what I can find. – Timothy Strimple Dec 12 '14 at 20:08
  • 1
    For example, this line from your last example ` db.collection("usercollection").findOne({'playerName': sPlayerName, 'playerId': sPlayerID}), function(err, result) {` isn't valid because your close the parenthesis before you pass in the function. If you actually used that code, you should have received something like: `SyntaxError: Unexpected token )`. – Timothy Strimple Dec 12 '14 at 20:09
  • Yes this was the function I made. The rest of the code isn't mine - someone else made a socket io game and I am simply modifying it and learning as I go. I did not get the SyntaxError }, I got the "TypeError: object is not a function" when using the findOne() method. (No problems with insert though, which confused me) - thanks again! – Entryton Dec 13 '14 at 01:24