【问题标题】:Subdocument function "pull" and "id" not working in Mongoose子文档功能“pull”和“id”在 Mongoose 中不起作用
【发布时间】:2021-02-08 22:41:14
【问题描述】:

我对 mongoose 和 nodejs 还很陌生,所以我在做我的项目时参考了 mongoose 文档。我想通过使用其 id 标识子文档来删除评论数组中的特定子文档。如图所示,我尝试使用“pull”和“id”方法进行操作。我在我的语法中也找不到任何错误,但它仍然有效。

这是来自我的数据库的示例文档:

{
  comments: [
    {
      replyComment: [],
      _id: 601a673735644c83e0aa1be3,
      username: 'xyz123@gmail.com',
      email: 'xyz123@gmail.com',
      comment: 'test123'
    },
    {
      replyComment: [],
      _id: 601a6c94d1653c618c75ceae,
      username: 'xyz123@gmail.com',
      email: 'xyz123@gmail.com',
      comment: 'reply test'
    },
    {
      replyComment: [],
      _id: 601eb7ba7233015d7090c6bf,
      username: 'xyz123@gmail.com',
      email: 'xyz123@gmail.com',
      comment: 'test comment'
    },
    {
      replyComment: [],
      _id: 601ec090f5f22d75b41bec7b,
      username: 'xyz123@gmail.com',
      email: 'xyz123@gmail.com',
      comment: 'test comment123'
    }
  ],
  _id: 601a3b8038b13e70405cf9ea,
  title: 'latest test',
  snippet: 'latest test snippet',
  body: 'latest test body',
  createdAt: 2021-02-03T05:58:24.123Z,
  updatedAt: 2021-02-07T06:56:53.902Z,
  __v: 15
}

通过这个测试 findById("601a3b8038b13e70405cf9ea") 和 console.log(result)

我的 topicSchema 文件:

const mongoose = require('mongoose');
const Schema =mongoose.Schema;

const topicSchema = new Schema({
    title: {
        type: String,
        required: true
    },
    snippet: {
        type: String,
        required: true
    },
    body: {
        type: String,
        required: true
    },
    comments: {
        type: Array,
        required: false
    }
}, {timestamps: true},{ versionKey: false });

const Topic = mongoose.model('Topic', topicSchema);
module.exports = Topic;

我的commentSchema 文件:

const mongoose = require('mongoose');
const Schema =mongoose.Schema;

const comSchema = new Schema({
    username: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true
    },
    comment: {
        type: String,
        required: true
    },
    replyComment: {
        type: Array,
        required: false
    },
}, {timestamps: true},{versionKey: false});

const Comm = mongoose.model('comm', comSchema);
module.exports = Comm;

【问题讨论】:

    标签: node.js mongodb express mongoose pull


    【解决方案1】:

    您尚未定义 topic 并且不要将 topic = result,, 一起使用,因为这不是必需的 这样做:

    result.comments.id(commId).remove();
    result.save()
    

    如果您想使用topic,请尝试

    let topic = result;
    topic.comments.id(commId).remove();
    topic.save()
    

    对于这个文档,您可以像这样使用update$pull

       Topic.updateOne(
        {
          _id: req.params.id,
        },
        {
          $pull: {
             "comments" : { _id: req.params.id1 } 
          },
        },
      ).then((res)=>{
        console.log(res)
      }).catch(err=>{
        console.log(err)
      });
    

    如果你可以使用 async/await 就试试

    app.delete('/topic/:id/comments/:id1',async(req,res)=>{
      let result = await Topic.findById(req.params.id);
      result.comments.id(req.params.id1).remove();
      let finalResult = await result.save()
      console.log(finalResult)
    })
    

    并使用 .then() .catch 方法:

     Topic.findById(res.params.id).then(result=>{
       let topic = result;
       topic.comments.id(res.params.id1).remove();
       topic.save().then(result=>{
         console.log(result)
       }).catch(err=>console.log(err))
     }
     ).catch(err=>{
      console.log(err)
    });
    

    注意:将 mongodb 更新到 4.4 并卸载 mongoose 模块并重新安装

    【讨论】:

    • 感谢您的建议,但我仍然遇到同样的错误。
    • 你能给我看看文件样本吗
    • 是的,我已经编辑了问题,请在那里查看
    • 谢谢Yaser,这三种方法我都试过了,输入参数也肯定是正确的,还有一些其他的猫鼬方法也不起作用。我认为猫鼬有问题,但我不确定。
    • 我测试了三种方法都很好,三种方法有同样的错误吗?
    猜你喜欢
    • 2019-07-16
    • 2020-12-01
    • 2018-05-02
    • 1970-01-01
    • 2023-03-18
    • 2017-08-13
    • 1970-01-01
    • 1970-01-01
    • 2017-03-09
    相关资源
    最近更新 更多