Mongoose Save Callback无效

时间:2017-12-03 05:11:52

标签: javascript node.js mongodb mongoose

我正在为一个使用MongoDB后端存储数据的简单Web应用构建服务器。我使用:

实例化一个新的mongoose连接
mongoose.connect('mongodb://localhost:27017/callback-newsfeed-db')

我的MongoDB输出似乎很好:

2017-12-02T21:00:53.277-0800 I NETWORK  [thread1] connection accepted from 127.0.0.1:52027 #86 (1 connection now open)
2017-12-02T21:00:53.291-0800 I NETWORK  [thread1] connection accepted from 127.0.0.1:52028 #87 (2 connections now open)
2017-12-02T21:00:53.291-0800 I NETWORK  [thread1] connection accepted from 127.0.0.1:52029 #88 (3 connections now open)
2017-12-02T21:00:53.292-0800 I NETWORK  [thread1] connection accepted from 127.0.0.1:52030 #89 (4 connections now open)
2017-12-02T21:00:53.292-0800 I NETWORK  [thread1] connection accepted from 127.0.0.1:52031 #90 (5 connections now open)

我还定义了一个模型如下:

const postSchema = mongoose.Schema({
  api: String,
  source: String,
  title: String,
  upvotes: Number
})

const Post = mongoose.model('Post', postSchema)

在我的一个服务器端点中,我有以下代码:

server.post('/posts', (request, response) => {
  console.log("INSIDE POSTS POST")
  const newapi = request.body.api
  const newsource = request.body.source
  const newtitle = request.body.title

  if(!newapi){
    response.send(422, "MUST PROVIDE API TYPE")
    return
  }else if(!newsource){
    response.send(422, "MUST PROVIDE RESOURCE SOURCE")
    return
  }else if(!newtitle){
    response.send(422, "MUST PROVIDE RESOURCE TITLE")
    return
 }

// Add a new post
  const newPost = new post.Post({
      api: newapi,
      source: newsource,
      title: newtitle,
      upvotes: UPVOTE_DEFAULT
  })
  console.log("ABOUT TO SAVE")

  // Save to DB and send to client
  newPost.save(error => {
      console.log("SAVE ERROR " )
      console.log(error)
      if(error){
          console.log("ERROR IN NEWPOST")
          throw error
      }else{
          console.log("STATUS OK")
          response.status(STATUS_OK)
          response.set({'Content-type': 'application/json'})
          response.send(JSON.stringify(newPost))
      }
      console.log("SAVE HAS COMPLETED")
  })
  console.log("AFTER NEW POST")
  })

现在,当我运行我的应用程序时,我在控制台中看到以下输出:

INSIDE POSTS POST
ABOUT TO SAVE
AFTER NEW POST

但是,出于某种原因(无论我等待多久),似乎没有调用newPost.save()回调的任何部分。 MongoDB输出并不表示明显的错误,所以我有点丢失。为什么会发生这种情况?

我对节点很陌生,所以对于如何调试或考虑可能的错误罪犯的任何想法都将不胜感激!

3 个答案:

答案 0 :(得分:0)

const newPost = new post.Post({

应该是

const newPost = new Post({

答案 1 :(得分:0)

你可以设置mongoose来使用ES6 Promises。

  mongoose.Promise = global.Promise;
  mongoose.connect(process.env.MONGODB_URI);

然后你可以使用

  newPost.save().then( () => {
    console.log('Everything went well');
  }).catch( (e) => {
    console.log('There was an error', e.message);
  });

答案 2 :(得分:0)

事实证明,问题似乎是我使用的MongoDB版本和mongoose之间不兼容。通过调用npm upgrade mongodb升级我的mongodb版本后,保存操作似乎已开始工作