0
$.post($gameNetwork._serverURL+'/addfriend', 
{username:"r",tusername:"w"}).done(function (data) {
console.log("finished");
 });



Account.statics.

    friend = function(name,tname,cb) {

        return this.findOneAndUpdate(

        { 'username':  name },

        { $push: {'friendlist': tname}},


        { upsert: true, new: true}, 

        cb);

    };

route

router.post('/addfriend',  function(req, res) {

//Account.findByName(req.body.username, function(err, account){
    Account.friend(req.body.username,req.body.tusername, function(err, account){
 if (err) {
      return res.status(203).json({
        err: err.msg
      });}
    if (!account) {
      return res.status(203).json({
        err: "Invalid username"
      });}
        var tname = req.body.tusername;

    var profile = {
        tname : tname,
      name: account.username,
      email: account.email,
      id: account._id,
      rank: account.rank
    };  });

this code should enter "w" in to the field 'friendlist' in Mongodb, but I got null instead of w.

how can I get "w" into the field 'friendlist' in Mongodb. Any help is appreciated Thanks in advance

Tosps
  • 73
  • 7

2 Answers2

0

router in an ExpressJS router?

If yes did you set the bodyParser middleware?

If not, set it like this

const express = require('express')
const bodyParser = require('body-parser')

const app = express()

// parse application/json
app.use(bodyParser.json())

You can also try to stringify the body in the ajax request like described here

Andrea Franchini
  • 548
  • 4
  • 14
0

You can debug your data of request like this:

router.post('/addfriend',  function(req, res) {
    console.log(req.body);
    // your logic
}

Run your code again, and you can see your data that you expect. If you see tusername = null or undefined, may be the problem in configure of your module that you use, example body-parser, busboy...vv

All comments are welcome!

trungquandev
  • 176
  • 1
  • 2
  • 10