简体   繁体   中英

Can't get MongoDB update query to work in Node.JS

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");
        }}; 

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
    });
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM