javascript - 值转换为字符串失败

标签 javascript node.js express mongoose bluebird

我有这个问题,我累了,我无法解决这个问题在路径“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;

这是我的所有代码

最佳答案

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

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

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

关于javascript - 值转换为字符串失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41679075/

相关文章:

javascript - 如何从 chrome 扩展程序调用网页上的 javascript 函数?

javascript - 将图像文件夹上传到 Firestore 存储并将下载 URL 放入 Firestore

javascript - Angular : iterate array with key value pairs

javascript - socket.io 房间不工作

node.js - Sequelize BelongsToMany 自引用反向 SQL QUERY

Javascript 将数据添加到 div

node.js - 找不到 'node' 的类型定义文件

node.js - windows 10 socket.io安装错误

node.js - TypeScript 编译时找不到外部模块

node.js - 从源 '...' 访问位于 'localhost:3000' 的 XMLHttpRequest 已被 CORS 策略阻止