猫鼬模型没有保存,没有抛出错误

时间:2019-03-14 18:27:39

标签: javascript node.js mongodb express mongoose

我的猫鼬模型(node / express应用程序)既不保存也不抛出错误,我也不知道为什么...

这是我的模特。它有一个帖子,通过架构ID引用了许多注释:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var CommentSchema = new Schema({
  body: {type: String, required: true, max: 2000},
  created: { type: Date, default: Date.now },
  flags: {type: Number, default: 0}
}, {
  writeConcern: {
    w: 0,
    j: false,
    wtimeout: 200
  }  
});

var PostSchema = new Schema({
  body: {type: String, required: true, max: 2000},
  created: { type: Date, default: Date.now },
  flags: {type: Number, default: 0},
  comments: [{ type: Schema.Types.ObjectId, ref: 'Comment' }]
}, {
  writeConcern: {
    w: 0,
    j: false,
    wtimeout: 200
  }  
});

var Post =  mongoose.model('Post', PostSchema);
var Comment = mongoose.model('Comment', CommentSchema)

module.exports = {
  Post: Post,
  Comment: Comment
} 

这是我的路线。它只是从传入的正文创建一个帖子,然后尝试保存它。它通过model.Post引用导出的帖子,因为导出的模块是一个对象。

var express = require('express');
var router = express.Router();
const fs = require('fs');
var model = require('../models/model');

router.post('/uploadPost', (req, res, next)=>{
  console.log('inside /uploadPost')
  console.log('value of req.files: ', req.files)
  console.log('value of req.body: ', req.body)

  var post = {
    body: req.body.post, 
    created: Date.now(),
    flags: 0, 
    comments: []
  }

  console.log('value of post: ', post)

  let postInstance = new model.Post(post)

  console.log('value of postInstance: ', postInstance)

  postInstance.save().then(post=>{
    console.log('value of post: ', post)
  }).catch( (e) => {
    console.log('There was an error', e.message);
  });

  res.json({return: 'return from /uploadPost'})
})

module.exports = router;

这是我的终端输出。它可以console.log进行所有操作,但保存回调或错误除外。我以为可能是res.json的争用条件,所以我将其放在了回调中,但这也没有任何作用。发生了什么事?

value of req.body:  { post: 'lkjlkjlk' }
value of post:  { body: 'lkjlkjlk',
  created: 1552587547653,
  flags: 0,
  comments: [] }
value of postInstance:  { flags: 0,
  comments: [],
  _id: 5c8a9b1ba7cece70037d3f46,
  body: 'lkjlkjlk',
created: 2019-03-14T18:19:07.653Z }

编辑:

我连接到猫鼬错了。。。

这是正确的连接代码(以上正确):

mongoose.connect("mongodb://localhost:27017/mydb");
mongoose.Promise = global.Promise;
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
db.once('open', function() {
  // we're connected!
  console.log('connected to mongoose db')
});

0 个答案:

没有答案