简体   繁体   中英

How do i update a object in mongoDB via nodeJS?

I'm attempting to make it so that when a player gets a highscore it searches there name, then it adds that highscore to there account. My issue is I don't know how to search for a name and update a tag using mongoose?

Here is my server code:

var mongoose = require("mongoose");
var bodyParser = require("body-parser");
var express = require("express");
var app = express();
var http = require("http").createServer(app);
var io = require("socket.io")(http);

var PORT = 3332;

app.use("/", express.static(__dirname));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

mongoose.connect("mongodb://localhost/endg", {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});
var db = mongoose.connection;
db.once("open", function (cb) {
  console.log("connection established");
});

io.on("connection", function (socket) {
  console.log("user connected");

  socket.on("chooseName", function (newName) {
    var data = {
      nickname: newName,
      highscore: 0,
    };
    db.collection("dat").findOne({ nickname: data.nickname }, function (
      err,
      doc
    ) {
      if (err) throw err;
      if (doc) {
        io.emit("nnTaken", null);
      } else {
        db.collection("dat").insertOne(data, function (err, coll) {
          if (err) throw err;
          console.log("rec estab");
          io.emit("newNickname", null);
        });
      }
    });
  });

  socket.on("player", function (player) {
    socket.on("highscore", function (hs) {
      console.log(player + ": " + hs);
      db.collection("dat").updateOne(
        { name: player },
        { $set: { highscore: hs } }
      );
      //This is where im trying to update but the above code does not work
    });
  });
});

http.listen(PORT, function () {
  console.log("server is up and running using port " + PORT);
});

How would i do this? I try using the update inside the highscore socket, so that when a highscore is achieved it updates that field but nothing is changing.

I actually figured it out. I'll post the answer in case anyone has this issue in the future.

var mongoose = require("mongoose");
var bodyParser = require("body-parser");
var express = require("express");
var app = express();
var http = require("http").createServer(app);
var io = require("socket.io")(http);

var PORT = 3332;

app.use("/", express.static(__dirname));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

mongoose.connect("mongodb://localhost/endg", {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});
var db = mongoose.connection;
db.once("open", function (cb) {
  console.log("connection established");
});

io.on("connection", function (socket) {
  console.log("user connected");

  socket.on("chooseName", function (newName) {
    var data = {
      nickname: newName,
      highscore: 0,
    };
    db.collection("dat").findOne({ nickname: data.nickname }, function (
      err,
      doc
    ) {
      if (err) throw err;
      if (doc) {
        io.emit("nnTaken", null);
      } else {
        db.collection("dat").insertOne(data, function (err, coll) {
          if (err) throw err;
          console.log("rec estab");
          io.emit("newNickname", null);
        });
      }
    });
  });

  socket.on("player", function (player) {
    socket.on("highscore", function (hs) {
      console.log(player + ": " + hs);
      db.collection("dat").findOne({ nickname: player }, function () {
        db.collection("dat").updateOne(
          { nickname: player },
          { $set: { highscore: hs } }
        );
      });
    });
  });
});

http.listen(PORT, function () {
  console.log("server is up and running using port " + PORT);
});

I went ahead and basically used findOne to find the players name, and then used updateOne with the $set to update the highscore value.

I'm guessing the issue was stemming from the fact that mongo wasn't able to tell which value i was trying to update.

Or if you prefer async function with es6

socket.on('highscore', async highscore => {
  await db.collection('dat').findOneAndUpdate(
    { nickname: player },
    { $set: { highscore: hs } }
  )
});

I'm using ES6 Javascript syntax. highscore => {} is the same as function (highscore)
Also I'm using async function. await means the program wait until the function is done

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