【问题标题】:i want to query all the document using findById query ( Ref ObjectId ) in mongoose我想在猫鼬中使用 findById 查询(Ref ObjectId)查询所有文档
【发布时间】:2021-05-08 16:13:11
【问题描述】:

目前正在构建笔记应用项目,我们可以在其中保存笔记,也可以编辑和删除笔记.. 突然卡在这里...我想查询( findById )与用户 ID 匹配的所有文档。在这种情况下,我在 Notes Schema 中将用户 ID 引用为 postedBy ..

这是我的用户 schmea 或模型...

import mongoose from 'mongoose'

const userSchema = new mongoose.Schema({   
    username: {
    type: String,
    required: [true, 'please provide username'],   
    },
    email: {
    type: String,
    required: [true, 'please provide email'],
    unique: true,
    index: true,   
    },   
    password: {
    type: String,
    required: [true, 'please provide password'],
    },   
    accountCreatedAt: {
    type: String,
    default: Date,   
   }, 

})

const User = mongoose.model('User', userSchema)

export default User

这是我的笔记架构,我将用户 ID 引用为 ref:

import mongoose from 'mongoose'

const noteSchema = new mongoose.Schema(
  {
    title: {
      type: String,
      required: [true, 'please provide title'],
      unique: true,
      trim: true,
    },
    text: {
      type: String,
      trim: true,
      required: [true, 'Please provide text'],
    },
    lable: {
      type: String,
      required: [true, 'please provide lable'],
    },
    postedBy: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'User',
      required: true,
    },
  },
  {
    timestamps: { createdAt: 'created_At', updatedAt: 'updated_At' },
  }
)

const Note = mongoose.model('Note', noteSchema)

export default Note

路由和控制器功能:

noteRoutes.get('/getNotesByUserID/:_id', noteController.getNotesByUserID)



export const getNotesByUserID = async (req, res, next) => {
  try {
    const id = req.params._id
    const userNotes = await Note.findById({ postedBy: id })

    res.status(200).json({
      status: 'success',
      data: {
        userNotes,
      },
    })
  } catch (error) {
    res.status(400).json({
      status: 'error',
      data: {
        message: error.message,
      },
    })
  }
}

当我尝试在邮递员中对此进行测试时,我收到以下消息:

    *"message": "Cast to ObjectId failed for value \"{ postedBy: '609554f9560327264b23d3fe' }\" at path \"_id\" for model \"Note\""*

提前谢谢...

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    mongoose findById 方法将 id 参数转换为模型的 _id 字段的类型,在您的情况下,此字段是 ObjectID 类型。

    但是,您将 id 参数作为对象 { postedBy: '609554f9560327264b23d3fe' } 传递,然后 mongoose 尝试执行以下操作:

    const castId = new ObjectId({ postedBy: '609554f9560327264b23d3fe' })
    

    这失败的原因很明显。

    因为findById 是一种通过_id 字段“快速”查找文档的自定义方法,所以您不应该使用它来查询其他字段。在您的演员阵容中,您应该改用findOne

    const userNotes = await Note.findOne({ postedBy: id })
    

    【讨论】:

    • 非常感谢您的回复.. 真的很感激.. 如果我使用 findOne 而不是 findById 它只会给我一个signle文档...我想检索所有与postedBy匹配的文档(参考 ID)
    • 那你应该用 find 代替
    猜你喜欢
    • 2013-10-21
    • 2015-06-26
    • 2017-06-01
    • 2013-04-16
    • 2020-07-02
    • 2022-01-17
    • 2019-10-19
    • 2014-03-21
    • 1970-01-01
    相关资源
    最近更新 更多