保存

时间:2016-11-30 13:17:17

标签: node.js mongodb mongoose

我有一个模特:

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},
});

现在收到对我服务器的POST请求后,我想向维基百科发出GET请求,并获取作者信息,然后将其作为对象附加到我的模型中,并将此模型写入我的数据库。

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');
  });
});

现在我尝试使用.pre函数更新值,但我得到了

  

quote.pre不是函数

这样做的正确方法是什么?我做错了什么?

1 个答案:

答案 0 :(得分:1)

quote不是Mongoose架构,但wordSchema是如此,它必须如下所示:

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

但实际上,根据我的理解,您在用例中并不需要它,您可以按照以下方式实现您的目标:

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');
    });
  });
});