简体   繁体   中英

Mongoose findOneAndUpdate doesn't find (or update) in Node

I'm trying to add user input (url's) to a database with Mongoose but also checking if the added data already exists. Instead it seems to be creating a new model every time.

This shows the res.json(input) on screen, not the test json

var mongo = require('mongodb');
var mongoose = require('mongoose');

var cors = require('cors');

// Basic Configuration 
var port = process.env.PORT || 3000;
process.env.DB_URI="omg it's my secret url"

// Connect to DB.
mongoose.connect(process.env.DB_URI, { useNewUrlParser: true, useUnifiedTopology: true }).
catch(error => handleError(error));

mongoose.connection.on('error', err => {
  console.log(err);
});

app.use(cors());



  //First we create a schema and Model in MongoDB.
  const urlSchema = new mongoose.Schema({ 
  original_url: String,
  short_url: Number 
  }); 

  const urlModel = mongoose.model('urlModel', urlSchema);

app.post(/PATH, function(req, res, done) {


  //Now we check if the input-url was actually valid.  
  if(!/(^https:\/\/)/.test(req.body.url)){
    res.json({error: "Invalid url"});
  } 

  //If it's valid we will start creating a model in the DB.
  else {
    var userUrl = req.body.url;
    var urlNumber = 0;

    var input = new urlModel({
      original_url: userUrl
    });


  //Now we check if the url was already added to the database and return a new or updated item.
    urlSchema.pre('save', function (next) {
      var query = {'original_url': userUrl };

      urlModel.findOneAndUpdate(query, userUrl, {upsert: true}, function(err, doc) {
      if (err) return res.send(500, {error: err});
      res.json({'test': 'test'});
      });
    });

      res.json(input);
      urlNumber++;

    input.save(function(err, data) {
      if (err) return console.log(err);
      done(null, data);
    });
  };
});

As you can see I also have a problem updating the number that I want to attach to the url in the database, since I re-assign 0 to urlNumber at the beginning of the call. Must be because it's late but I can't seem to find a way to update that number correctly. I tried two variables and checking them against each other and an if(urlNumber > 0), but that's a problem I'm still solving. Seems so simple..

Anyway the question here is: why doesn't findOneAndUpdate seem to update? The returned res.json(input) shows a new '_id' every time, which tells me it does actually create new models every run.

Example returns

#1

{
_id: eksdjh3948wryeids293ren12;
original_url: "https://www.correct.com"
short_url: 0
}



#2

{
_id: eksdjh3948wryeids293ren13; // (<----- NEW NUMBER)
original_url: "https://www.correct.com"
short_url: 0
}

Your pre('save' function(next) {}) hook isn't calling next()

Turns out the.pre hook doesn't work with findOneAndUpdate, If I just remove that. the code now works as expected.

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