如何使用其他数据更新现有对象

时间:2019-11-27 14:59:50

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

该项目是使用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

4 个答案:

答案 0 :(得分:1)

我不确定,但是注释是一个对象而不是数组,因此您不能使用[... this.comments]进行推送,而我认为这是您要推送的注释?

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

答案 1 :(得分:1)

从您的架构注释不是数组。您正在尝试将对象散布到数组中。 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}})

答案 2 :(得分:1)

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

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

您可以检查打印类型:

console.log(typeof this.comments)

甚至,甚至是整个对象:

console.log(this.comments)

如您所见,在两种情况下,您都得到一个对象,而不是列表(您如何看待)

所以您可以做两件事:

1- 可迭代的列表

this.comments 是一个对象,但是在该对象中您具有所需的列表,因此只需使用该列表即可。

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

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

2- 注释为架构中的列表

将注释属性定义为列表

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

};

答案 3 :(得分:1)

不要使用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
        });
      }
    });
  });
});