5

When I add the line "{ upsert: true }", I got this error:

TypeError: callback.apply is not a function

// on routes that end in /users/competitorAnalysisTextData
// ----------------------------------------------------

router
  .route('/users/competitorAnalysisTextData/:userName')

  // update the user info (accessed at PUT http://localhost:8080/api/users/competitorAnalysisTextData)
  .post(function (req, res) {
    // use our user model to find the user we want
    User.findOne({userName: req.params.userName}, function (err, user) {
      if (err) res.send(err);

      console.log(
        'user.competitorAnalysis.firstObservation: %@',
        user.competitorAnalysis.firstObservation,
      );
      // Got the user name
      var userName = user.userName;
      // update the text data
      console.log('Baobao is here!');
      user.update(
        {
          userName: userName,
        },
        {
          $set: {
            'competitorAnalysis.firstObservation': req.body.firstObservation,
            'competitorAnalysis.secondObservation': req.body.secondObservation,
            'competitorAnalysis.thirdObservation': req.body.thirdObservation,
            'competitorAnalysis.brandName': req.body.brandName,
            'competitorAnalysis.productCategory': req.body.productCategory,
          },
        },
        {upsert: true},
      );

      // save the user
      user.save(function (err) {
        if (err) return res.send(err);

        return res.json({message: 'User updated!'});
      });
    });
  });

Without this line, there is no error. I'm new to nodejs, not very sure where the problem is.

Update

No error message now, but this part of the database is not updated with new data. The embedded document is still empty.

// on routes that end in /users/competitorAnalysisTextData
// ----------------------------------------------------
router
  .route('/users/competitorAnalysisTextData/:userName')

  // update the user info (accessed at PUT http://localhost:8080/api/users/competitorAnalysisTextData)
  .post(function (req, res) {
    console.log('1');

    // Just give instruction to mongodb to find document, change it;
    // then finally after mongodb is done, return the result/error as callback.
    User.findOneAndUpdate(
      {userName: req.params.userName},
      {
        $set: {
          'competitorAnalysis.firstObservation': req.body.firstObservation,
          'competitorAnalysis.secondObservation': req.body.secondObservation,
          'competitorAnalysis.thirdObservation': req.body.thirdObservation,
          'competitorAnalysis.brandName': req.body.brandName,
          'competitorAnalysis.productCategory': req.body.productCategory,
        },
      },
      {upsert: true},
      function (err, user) {
        // after mongodb is done updating, you are receiving the updated file as callback
        console.log('2');
        // now you can send the error or updated file to client
        if (err) return res.send(err);

        return res.json({message: 'User updated!'});
      },
    );
  });

0

2 Answers 2

11

There are 2 ways to update documents in mongodb:

  1. find the document, bring it to server, change it, then save it back to mongodb.

  2. just give instruction to mongodb to find document, change it; then finally after mongodb is done, return the result/error as callback.

In your code, you are mixing both methods.


  1. with user.save(), first you search the database with user.findOne, and pull it to server(nodejs), now it lives in your computer memory. then you can manually change the data and finally save it to mongodb with user.save()

    User.findOne({ userName: req.params.userName}, function(err, user) {
    
        if (err)
            res.send(err);
    
        //this user now lives in your memory, you can manually edit it
        user.username = "somename";
        user.competitorAnalysis.firstObservation = "somethingelse";
    
        // after you finish editing, you can save it to database or send it to client
         user.save(function(err) {
            if (err)
                return res.send(err);
    
            return res.json({ message: 'User updated!' });
        });
    
  2. the second one is to use User.findOneAndUpdate().. This is preferred, instead of user.findOne() then user.update(); because those basically searching the database twice. first to findOne(), and search again to update()

Anyway,the second method is telling mongodb to update the data without first bringing to server, Next, only after mongodb finish with its action, you will receive the updated-file (or error) as callback

User.findOneAndUpdate({ userName: req.params.userName}, 
            {
             $set: { "competitorAnalysis.firstObservation" : req.body.firstObservation,
                      "competitorAnalysis.secondObservation" : req.body.secondObservation,
                      "competitorAnalysis.thirdObservation" : req.body.thirdObservation,
                      "competitorAnalysis.brandName" : req.body.brandName,
                      "competitorAnalysis.productCategory" : req.body.productCategory
            } },
            { upsert: true },
        function(err, user) {
        //after mongodb is done updating, you are receiving the updated file as callback    

        // now you can send the error or updated file to client
        if (err)
            res.send(err);

        return res.json({ message: 'User updated!' });
        });
Sign up to request clarification or add additional context in comments.

6 Comments

I think you explain very well and try to follow the second suggested way. However, I still get the same error message. Could you please help me a little bit more and have a look at my Update section in the post?
I hope this one works, actually you passed 5 arguments, findOneAndUpdate() accept 4 arguments. The 4th is the callback mongoosejs.com/docs/api.html#query_Query-findOneAndUpdate
Yes, very helpful.
Sorry... there is no error message now. But this part of the database is still not updated with new data. The embedded document is still empty. The Update is the latest...
I am not sure, the code seems correct, with {upsert: true}, you are telling mongodb to create new document if the query does not match anything.. maybe you can log the error, or try to $set one document to check any error
|
2

You forgot to pass a callback to the update method

user.update(
  {
    $set: {
      'competitorAnalysis.firstObservation': req.body.firstObservation,
      'competitorAnalysis.secondObservation': req.body.secondObservation,
      'competitorAnalysis.thirdObservation': req.body.thirdObservation,
      'competitorAnalysis.brandName': req.body.brandName,
      'competitorAnalysis.productCategory': req.body.productCategory,
    },
  },
  {upsert: true},
  function (err, result) {},
);

update method expects 3 arguments.

  • document update
  • options
  • callback

2 Comments

I still find the same error after adding the callback. Could you please see the Update section in my post?
@ChenyaZhang You pass extra arguments to that function. Check it out

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.