Miha Šušteršič Miha Šušteršič - 4 days ago 5
Node.js Question

mongoose update model before saving

I have a model:

const wordSchema = mongoose.Schema({
author: {type: Object, default: 'unknown'},
quote: String,
source: {type: String, default: 'unknown', index: true},
rating: {type: Number, default: 0},
createdAt: {type: Date, default: Date.now},
updatedAt: {type: Date, default: Date.now},
});


Now after receiving a POST request to my server, I want to make a GET request to wikipedia, and get the author info, then append it to my model as an object, and write this model into my database.

app.post('/', function(req, res) {
let author = {};
let quote = new Word({
author: req.body.author,
quote: req.body.quote,
source: req.body.source,
rating: req.body.rating,
});
let authorName = req.body.author.replace(/ /g, '%20');
let url = 'https://en.wikipedia.org/w/api.php?action=query&format=json&titles=' + authorName + '&prop=pageimages|extracts&pithumbsize=200&exsentences=10&exintro=true';
request.get(url, (error, response, body) => {
if(error) {
return error;
}
let data = JSON.parse(body);
let pageID;
for(page in data.query.pages) {
pageID = page;
}
author = {
name: req.body.author,
thumbnail: data.query.pages[pageID].thumbnail.source,
flavorText: data.query.pages[pageID].extract,
};
});
// Save the quote
quote.pre('save', (next) => {
this.author = author;
})
quote.save(function(err, quote) {
if (err) {
res.send(err);
}
res.redirect('/words');
});
});


Now I tried updating the value with the
.pre
function, but I am getting


quote.pre is not a function


What would be the 'correct way of doing this and what am I doing wrong?

Answer

quote is not a Mongoose schema, but wordSchema is so it needs to be as follow:

wordSchema.pre('save', (next) => {
  this.quote = whteverYouWantToAssignWith;
})

But actually you don't need it in your use case as far as I understand, you may achieve what you want as follow:

app.post('/', function(req, res) {
  let authorName = req.body.author.replace(/ /g, '%20');
  let url = 'https://en.wikipedia.org/w/api.php?action=query&format=json&titles=' + authorName + '&prop=pageimages|extracts&pithumbsize=200&exsentences=10&exintro=true';
  request.get(url, (error, response, body) => {
    if(error) {
      return error;
    }
    let data = JSON.parse(body);
    let pageID;
    for(page in data.query.pages) {
      pageID = page;
    }

    let quote = new Word({
      author: {
        name: req.body.author,
        thumbnail: data.query.pages[pageID].thumbnail.source,
        flavorText: data.query.pages[pageID].extract,
      },
      quote: req.body.quote,
      source: req.body.source,
      rating: req.body.rating,
    });

    quote.save(function(err, quote) {
      if (err) {
        res.send(err);
      }
      res.redirect('/words');
    });
  });
});
Comments