【问题标题】:How to update existing object with additional data如何使用附加数据更新现有对象
【发布时间】:2019-11-27 14:59:50
【问题描述】:

项目是用 nodejs 和 mongoose 创建的。我要做的是使用附加数据更新现有模型(在这种情况下是注释)。

这是模型及其方法:

const bugSchema = new Schema({
    title: {
        type: String,
        required: true
    },
    description: {
        type: String,
        required: true
    },
    date: {
        type: String,
        required: true
    },
    time: {
        type: String,
        required: true
    },
    assignedTo: {
        type: String,
        required: true
    },
    assignedBy: {
        type: String,
        required: true
    },
    status: {
        type: String,
        required: true
    },
    priority: {
        type: String,
        required: true
    },
    comments: {
        comment:[
            {
                user:{
                    type: String,
                    required: true
                },
                content: {
                    type: String,
                    required: true
                }
            }
        ]
    }

});

bugSchema.methods.addComment = function(comment){
    const username = comment.user;
    const content = comment.content;
    console.log(comment);
    const updatedComments = [...this.comments];
    updatedComments.push({
       user : username,
       content: content
    });
    this.comments = updatedComments;
    return this.save();

};

从表单传递信息的控制器:

exports.postComment =  (req,res,next) =>{
    const bugId = req.body.bugID;
    const name = req.session.user.fullName;
    const content = req.body.content;
    const prod = {name, content};

    Bug.findById(bugId).then(bug =>{
        return bug.addComment(prod);
    })
        .then(result =>{
            console.log(result);
        });


};

我收到以下错误:

(node:3508) UnhandledPromiseRejectionWarning: TypeError: this.comments is not iterable

【问题讨论】:

    标签: javascript node.js model-view-controller mongoose


    【解决方案1】:
    (node:3508) UnhandledPromiseRejectionWarning: TypeError: this.comments is not iterable
    

    该错误表明您正在尝试迭代一种不具有该功能的数据。

    您可以检查打印类型:

    console.log(typeof this.comments)
    

    甚至,打印整个对象:

    console.log(this.comments)
    

    如你所见,在这两种情况下,你得到的是一个对象,而不是一个列表(你怎么看)

    所以你可以做两件事:

    1- 可迭代列表

    this.cmets 是一个对象,但在该对象中你有你想要的列表,所以只需使用该列表。

    bugSchema.methods.addComment = function(comment){
        const username = comment.user;
        const content = comment.content;
        console.log(comment);
        //const updatedComments = [...this.comments];
        const updatedComments = [...this.comments.comment];
        updatedComments.push({
           user : username,
           content: content
        });
        this.comments = updatedComments;
        return this.save();
    };
    

    或者您可以修改架构,使 cmets 成为列表而不是对象

    2- cmets 作为架构中的列表

    将 cmets 属性定义为列表

    const bugSchema = new Schema({
        title: {
            type: String,
            required: true
        },
        description: {
            type: String,
            required: true
        },
        ...
        ...,
        comments:[
            {
                user:{
                    type: String,
                    required: true
                },
                content: {
                    type: String,
                    required: true
                }
            }
        ]
    });
    

    然后,尝试按照你的做法对其进行迭代

    bugSchema.methods.addComment = function(comment){
        const username = comment.user;
        const content = comment.content;
        console.log(comment);
        const updatedComments = [...this.comments];
        updatedComments.push({
           user : username,
           content: content
        });
        this.comments = updatedComments;
        return this.save();
    
    };
    

    【讨论】:

      【解决方案2】:

      我不确定,但是 cmets 是一个对象而不是一个数组,所以你不能使用 [...this.cmets] 推送,我认为这是你想要推送的评论?

      const updatedComments = [...this.comment];
      updatedComments.push({
         user : username,
         content: content
      });
      this.comment = updatedComments;
      

      【讨论】:

        【解决方案3】:

        从您的架构中,cmets 不是一个数组。您正在尝试将对象传播到数组中。 const updatedComments = [...this.comments]; 也在数组上推送作品。 尝试通过在 bugSchema 之外声明 commentSchema 来修改您的架构定义。

        const commentSchema = new Schema({
             user:{
                    type: String,
                    required: true
              },
              content: {
                    type: String,
                    required: true
              }
        })
        
        
        const bugSchema = new Schema({
          
          comments: {
            type: [commentSchema]
          }
        
        })

        Bug.findByIdAndUpdate(bugId, {$push: {comments: newComment}})

        【讨论】:

          【解决方案4】:

          不要使用findByIdAndUpdate猫鼬方法,你最好使用save

          写在这里https://mongoosejs.com/docs/tutorials/findoneandupdate.html

          The findOneAndUpdate() function in Mongoose has a wide variety of use cases. You should use save() to update documents where possible, but there are some cases where you need to use findOneAndUpdate(). In this tutorial, you'll see how to use findOneAndUpdate(), and learn when you need to use it.

          下面是一个路由器示例

          router.put('/items', (req, res) => {
            if (!req.body._id || !req.body.title) {
              return res.status(501).send({ message: 'Missing parameters, or incorrect parameters' });
            }
          
            return itemModel.findOne({ _id: req.body._id }, (err, item) => {
              if (err) {
                return res.status(500).send({
                  message: err
                });
              }
          
              item.title = req.body.title; // <------------- You rewrite what was before stored on title attribute
          
              return item.save((err, item) => { // <------------- You save it, this is not gonna create a new one, except if it doesn't exist already
                if (err) {
                  return res.status(400).send({
                    message: 'Failed to update item'
                  });
                } else {
                  return res.status(200).send({
                    message: 'Item update succesfully',
                    data: item
                  });
                }
              });
            });
          });
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2021-11-13
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-03-24
            相关资源
            最近更新 更多