强制转换为字符串失败

时间:2017-01-16 14:52:13

标签: javascript node.js express mongoose bluebird

我有这个问题我累了我无法解决这个问题Cast to string failed for value \"{}\" at path \"post\

{
  "confirmation": "fail",
  "message": {
    "message": "Cast to string failed for value \"{}\" at path \"post\"",
    "name": "CastError",
    "stringValue": "\"{}\"",
    "kind": "string",
    "value": {

    },
    "path": "post"
  }
}
希望你能帮助我

的index.html

    <h1>CreateComment</h1>
    <form action="/api/comment" method="post">
      <input type="text" name="post" placeholder="Post" /><br />
      <input type="text" name="text" placeholder="Text"><br />
      <input type="submit" value"Create" />
    </form>

Comment.js

var mongoose = require('mongoose')

var CommentSchema = new mongoose.Schema({
  profile: {type: mongoose.Schema.Types.Mixed, default: {}},
  post: {type: String, default:{}},
  text: {type: String, default: ''},
  timestamp: {type:Date, default:Date.now}
})

module.exports = mongoose.model('CommentSchema', CommentSchema);

controllers.js

var Comment = require('../models/Comment')
var promise = require('bluebird')

module.exports = {

  post: function(params, isRaw) {
    return new Promise(function(resolve, reject) {
      Comment.create(params, function(err, comment) {
        if (err) {
          reject(err)
          return
        }
        console.log(comment)
        resolve(comment)
      })
    })
  }

}

api.js

var express = require('express');
var router = express.Router();
var controllers = require('../controllers');


router.post('/:resource', function(req, res, next) {
  var resource = req.params.resource;
  var controller = controllers[resource];

  if (controller == null) {
    res.json({
      confirmation: 'fail',
      message: 'Invalid Resource'
    })

    return
  }

  controller.post(req.body, false)
    .then(function(result) {
      res.json({
        confirmation: 'success',
        result: result
      })
    })
    .catch(function(err) {
      res.json({
        confirmation: 'fail',
        message: err
      })
    })
})

module.exports = router;

这是我的所有代码

1 个答案:

答案 0 :(得分:1)

我认为{}不是'post'成员的有效默认值。

post: {type: String, default:{}},

'post'默认值应该是一个字符串,你需要提供一个或一个空对象,然后该类型不应该是“String”。