Friday, 1 March 2019

Mongoose model not updated in findOneAndUpdate

I have a POST route in an express app that aims to update a mongoose model based on form input. The "Base" model is Profile, and I have two discriminator models Helper and Finder that conditionally add fields to the Profile schema.

Thus, req.body.profile will contain different fields depending on the discriminator it's associated with, but will always contain the fields (username, email city, accountType) present in the "base" model, Profile.

Before I send my PUT request, an example of a document in Profile looks like this:

{ jobTitle: '',
  lastPosition: '',
  email: '',
  city: '',
  accountType: 'helper',
  _id: 5c77883d8db04c921db5f635,
  username: 'here2help',
  __v: 0 }


This looks good to me, and suggests that the model is being created as I want (with base fields from Profile, and those associated with the Helper model - see below for models).

My POST route then looks like this:

router.put("/profile/:id", middleware.checkProfileOwnership, function(req, res){

    console.log(req.body.profile);

    Profile.findOneAndUpdate(req.params.id, req.body.profile, function(err, updatedProfile){

        if(err){
            console.log(err.message);
            res.redirect("/profile");
        } else {
            console.log(updatedProfile);
            res.redirect("/profile/" + req.params.id);
        }

    });
});

The information I receive from the form (console.log(req.body.profile)) is what I expect to see:

{ accountType: 'helper',
  username: 'here2help',
  email: 'helpingU@me.com',
  city: 'New York',
  jobTitle: 'CEO',
  lastPosition: 'sales rep'}

And after the Profile.findOneAndUpdate():

console.log(updatedProfile)

{ jobTitle: '',
  lastPosition: '',
  email: 'helpingu@me.com',
  city: 'New York',
  accountType: 'helper',
  _id: 5c77883d8db04c921db5f635,
  username: 'here2help',
  __v: 0 }

So, the fields that are defined in my 'Base' model (ie those defined in ProfileSchema - see below) are being updated, but those that are in my discriminators are not - (see below and my related question).

The updated information is clearly present in req, but is not propagated to the Profile model - How can this be?

I've also tried using findByIdAndUpdate but I get the same result.

Here is models/profile.js where I define the schemas:

var options = { discriminatorKey: 'accountType' };

var profileSchema = new mongoose.Schema({ 
    username: String,
    email: { type: String, default: "" },
    city: { type: String, default: "" }
}, options);

profileSchema.plugin(passportLocalMongoose);

var Profile = mongoose.model('Profile', profileSchema);

var Helper = Profile.discriminator('helper', new mongoose.Schema({
    jobTitle: { type: String, default: "" },
    lastPosition: { type: String, default: "" },
}));

var Finder = Profile.discriminator('finder', new mongoose.Schema({
    position: { type: String, default: "" },
    skills: Array
}));


module.exports = Profile;

This is my first attempt at using discriminators in mongoose, so it's more than possible that I am setting them up incorrectly, and that this is the root of the problem.

Please let me know if this is unclear, or I need to add more information.



from Mongoose model not updated in findOneAndUpdate

How to convert html template which load external html to reactjs

I'm working on web porject, I want to use reactjs, the template I'm using calls external js files which loads remote html file. for example

<header role="banner">
  <script type="text/javascript" src="/remote/webassets/js/header-footer.js"></script>
</header>

I thought of converting the above to react like the following

import React, {
  Component,
} from 'react';

// loads header and footer
class HF extends Component {

  render() {
    return (
      <header role="banner">
        <script type="text/javascript" src="/remote/webassets/js/header-footer.js"></script>
      </header>
    );
  }
}

export default HF;

my template

    <body>
  <header role="banner">
    <!-- loads header and footer -->
    <script type="text/javascript" src="/remote/webassets/js/header-footer.js"></script>
  </header>

  <div class="sidebar">
    <!-- loads sidebar menu  -->
    <script type="text/javascript" src="/remote/webassets/js/sidebar.js"></script>
  </div>

  <main>
    <!-- content -->
  </main>
  <footer class="footer"></footer>
  <script>
    $(window).load(function() {
      $('[data-class=lazyload]').each(function() {

        //* set the img src from data-src

        $(this).attr('href', $(this).attr('data-href'));


      });
      $('.lazyload').each(function() {

        //* set the img src from data-src

        $(this).attr('src', $(this).attr('data-src'));

      });
    });

    const loadScriptAsync = () {...};
    window.onload = loadScriptAsync

    (function() {
      'use strict';

      window.MyEvenArray = function(callback) {...};

      window.ErrorEvents = new window.MyEvenArray();

      window.onerror = function(msg, url, line, col, error) {
        ...
        window.ErrorEvents.push(d);
      };
    })();
  </script>
</body>

Is there a better way converting this to react or should I just stick to using plain html?



from How to convert html template which load external html to reactjs

How to get POST global variable in PHP Symfony 4?

Actually, I have a very strange problem getting the result of a POST global variable in Symfony 4.

I tried this way :

$date = $request->request->get('date');

This is how I actually send the AJAX request when the Calendar input's date changed :

onSelect: function(date, instance) {
    $.ajax({
      url : 'home',
      type : 'POST',
      data : {'date':date},
      dataType : 'html',
      success : function(code_html, statut){
        console.log(statut);
      },

      error : function(resultat, statut, erreur){

      },

      complete : function(resultat, statut){

      }          
    });

The onSelect callback successfully receive the date value I want.

And this result shows the 200 success code with right values for the date variable :

enter image description here

But $date still be NULL :(



from How to get POST global variable in PHP Symfony 4?