node.js - 当我尝试将对象推送到 MongoDB 和 Nodejs 中的数组时,为什么会出现castError?

标签 node.js mongodb mongoose nosql backend

我有一个 mongoDB,我正在尝试制作一个 Nodejs 服务器来操作数据库中的数据。当我尝试将 Comment 推送到 BlogPost 对象中的 Comments 数组时,出现了castError。

下面是源代码,如果您缺少重要信息,请告诉我。 提前致谢!

路线:

routes.post('/comments/push/:id', function(req, res) {
const blogPostId = req.param('id');
const commentProps = req.body;

BlogPost.findById(blogPostId)
  .then((blogPost) => {
    blogPost.comments.push(commentProps);
    return blogPost.save();
  })
    .then((blogPost) => res.status(200).json({
    'status': 'Comment is deleted.',
    'comment': blogPost
}))
.catch((error) => res.status(400).json(error)) });

BlogPost 架构:

const BlogPostSchema = new Schema({
content: {
type: String,
validate: {
  validator: (content) => content.length > 5,
  message: 'Content must contain at least 6 characters.'
},
required: [true, 'Content must be filled in.']
},
rating: Number,
user: { type: Schema.Types.ObjectId, ref: 'user' },
board: {type: Schema.Types.ObjectId, ref: 'board'},
comments: [{
  type: Schema.Types.ObjectId,
  ref: 'comment'
  }]
});

评论架构:

const CommentSchema = new Schema({
content: {
type: String,
validate: {
  validator: (content) => content.length > 5,
  message: 'Content must contain at least 6 characters.'
},
required: [true, 'Content must be filled in.']
},
user: { type: Schema.Types.ObjectId, ref: 'user' },
rating: Number

// board: Board
});

这是 postman 中的错误: postman screen

非常感谢您的帮助!

最佳答案

  1. 首先确保您在 req.body 中收到的是什么,这不好 直接从 req.body 存储。
  2. 第二个引用文献。注释 Schema 方面是 objectId,而 req.body 是 对象本身。我不确定你要做什么,但它 类似 blogPost.comments.push(req.body.someValidId);

第三个为什么 2 个查询用于简单更新。您可以使用 $push、$addToSet 直接推送到评论,或使用 $pull 从评论中删除。

BlogPost.findOneAndUpdate({
    _id:blogPostId
}, {
    $addToSet:{
        comments : someValidId
    }
}, {
    new :true,
    upsert:false
})
.then((blogPost) => {
    res.status(200).json({
        'status': 'Comment is deleted.',
        'comment': blogPost
    })
})
.catch((error) => 
    res.status(400).json(error)) 
});

关于node.js - 当我尝试将对象推送到 MongoDB 和 Nodejs 中的数组时,为什么会出现castError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47681039/

相关文章:

node.js - 使用 mongoose 填充到 "join"匹配的子记录

javascript - Mongo/mongoose $facet 过滤器,如果客户应用过滤器,则返回所有产品的品牌/标签作为响应

node.js - Mongoose 返回不一致的结果

javascript - 如何在 OS X 中将 NODE_ENV 设置为生产/开发

node.js - 是否可以在 NodeJS 中的 'newListener' 事件的事件监听器回调中发出事件?

mongodb - Couchdb 中任意谓词查询的策略

mongodb - 为什么我的 Mongoose 模型无法加载?

javascript - 使用此错误编写 nodeJS 脚本

php - 在 Ubuntu 14 上将 PHP Mongo 扩展更新到 1.5

node.js - 无法从 Mongoose DB 检索数据?返回空白结果?