簡體   English   中英

如何查找類型為 objectId 的鍵,參考<some model></some>

[英]How to find key with type objectId , ref to <some model>

我創建了一個 Notes model,其架構如下所示

const notesschema = new Schema({
user :{
    type : Schema.Types.ObjectId,
    ref : 'User',
    required : true
},
problem : {
    type : Schema.Types.ObjectId,
    ref : 'Problems',
    required : true
},
content : {
    type : 'string'
}
 },{
timestamps : true
})

為了向用戶展示他對特定任務/問題的筆記,我正在嘗試獲取筆記並向他展示,如果他做了一些更改並保存,可能會更新,問題在於這個模式我不知道如何寫 <model.findById >從我的筆記 model 中查找具有特定用戶和特定任務/問題的筆記的 API。我會知道它的 ID。

有了這個特定的模式,以及我目前的知識,我將不得不編寫這么多代碼。 因此,如果有任何更簡單的方法來完成這項任務,歡迎,
我也在考慮改變我的架構,只是將我的用戶 ID 放在我的架構中而不是整個用戶並從我的數據庫中查找注釋

const notesschemaOfUser = await notesschema.findOne({user: user_id});

你創建筆記的集合的方式和你做的一樣,

const notesSchema = new mongoose.Schema({
  user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User', // # the name of the user model
    required: true
  },
  problem: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Problem', // # the name of the user model
    required: true
  },
  content: String
})

然后,您將創建 notesSchema 的 model,如下所示:

const NoteModel = mongoose.model('Note', notesSchema, 'notes')

導出它們以便您可以在控制器中使用它們:

module.exports = {
  NoteModel,
  notesSchema
}

或者如果您使用的是 +es6 模塊(想想,如果您使用的是 TypeScript):

export default {
  NoteModel,
  notesSchema
}

這將導致在數據庫中創建下表(集合):

在此處輸入圖像描述

讓我們考慮以下挑戰:

要獲取所有注釋:

NoteModel.find({})

獲取所有用戶:

UserModel.find({}) // you should have something like this in your code of course

得到所有的問題:

ProblemModel.find({}) // you should have something like this in your code of course

獲取用戶的所有筆記:

NotesModel.find({ user: USER_ID })

要按問題搜索筆記

NotesModel.find({ problem: PROBLEM_ID })

現在,以上是您在 mongoose 中的操作方式,現在讓我們為所有這些創建一個 RESTFUL controller:(假設您使用的是 express)

const expressAsyncHandler = require('express-async-handler') // download this from npm if you want
app.route('/notes').get(expressAsyncHandler(async (req, res, next) => {
  const data = await NotesModel.find(req.query)
  res.status(200).json({
    status: 'success',
    data,
  })
}))

req.query將包含搜索過濾器,搜索過濾器將由客戶端(前端)發送,如下所示:

http://YOUR_HOST:YOUR_PORT/notes?user=TheUserId
http://YOUR_HOST:YOUR_PORT/notes?problem=TheProblemId
http://YOUR_HOST:YOUR_PORT/notes?content=SomeNotes

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM