简体   繁体   English

尝试将对象推入MongoDB和Nodejs中的数组时,为什么会出现castError?

[英]Why do I get a castError when I try to push an object to an array in MongoDB and Nodejs?

I have a mongoDB and I am trying to make a Nodejs server to manipulate the data in the database. 我有一个mongoDB,我正在尝试制作一个Nodejs服务器来操纵数据库中的数据。 I get a castError when I try to push a Comment to the Comments array in a BlogPost object. 当我尝试将Comment推送到BlogPost对象中的Comments数组时,我得到一个castError。

Source code below, please tell me if you're missing important information. 下面的源代码,如果您缺少重要信息,请告诉我。 Thanks in advance! 提前致谢!

The route: 路线:

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)) });

The BlogPost schema: 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'
  }]
});

The Comment schema: 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
});

Here is the error in postman: postman screen 这是邮递员中的错误: 邮递员屏幕

Help would be greatly appreciated! 帮助将不胜感激!

  1. first make sure what's you are receiving in req.body, it's not good to store directly from req.body. 首先确保您在req.body中收到什么,直接从req.body中存储是不好的。
  2. second ref. 第二参考。 comments Schema aspect a objectId while req.body is Object itself. 注释架构方面是一个objectId,而req.body是Object本身。 i'm not sure what are you going to do but it something like blogPost.comments.push(req.body.someValidId); 我不确定您要做什么,但是类似blogPost.comments.push(req.body.someValidId);

third why 2 queries for simple update. 第三,为什么2查询简单更新。 you can use $push, $addToSet to push directly to comments or $pull to remove from comments. 您可以使用$ 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)) 
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何添加新的 object 或推入数组 Mongodb Compass NodeJS Express(更新不是功能)? - How do I add new object or push into array Mongodb Compass NodeJS Express (update is not a function)? 我试图从mongodb获取单个数组值,但是当我尝试时,我得到了整个对象 - I am trying to get a single array value from mongodb, but when i try i get the whole object 我如何使用节点 $push 到 mongoDB 数据库中数组中的对象? - How do i $push to a object in an array in a mongoDB database with node? 如何使用nodejs和mongodb获取另一个对象内部的对象? - How do I get an object that is inside another with nodejs and mongodb? 尝试将中间件功能导出到module.exports对象时,为什么会得到“下一个不是功能”的信息? - Why do I get 'Next is not a function' when I try to export a Middleware function to module.exports object? 当我尝试连接到 mongodb 时出现此错误 - when i try to connect to mongodb get this error Nodejs/MongoDB:将动态创建的对象推入数组 - Nodejs/MongoDB: Push dynamically created object into array 当我尝试将 Object 从 api 添加到我的 mongodb atlas db NODE.JS 时,我变得不确定 - I get undefined when i try to add an Object from an api to my mongodb atlas db NODE JS 为什么我得到 am CastError: Cast to ObjectId failed? - Why I get am CastError: Cast to ObjectId failed? 为什么在nodejs中`或`大量时我得到负值? - Why do I get negative value when `or` a large number in nodejs?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM