Home > Software engineering >  How to find key with type objectId , ref to <some model>
How to find key with type objectId , ref to <some model>

Time:01-31

I have created a Notes model having schema as shown below

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

To show the User his notes for a particular task/problem I am trying to fetch notes and show to him and possibly update if he do some changes and save, The problem is with this schema I dont know how to write <model.findById >API to find notes from my notes model having particular user and specific task/problem.Which I would know the Id of.

With this particular schema , and my current knowledge i would have to write So much code. So if there is any easier way to do this task is welcomed,
I was also thinking to change my schema and just placing my user id in my schema instead of whole user and finding notes from my database

CodePudding user response:

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

CodePudding user response:

You create the notes' collection the same way you're doing it,

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

Then you'll create the model of the notesSchema as follows:

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

export them so you can use them in your controllers:

module.exports = {
  NoteModel,
  notesSchema
}

or if you're using es6 modules (think of, if you're using TypeScript):

export default {
  NoteModel,
  notesSchema
}

This will result in creating the following table (collection) in the database:

enter image description here

Let's think of the following challenges:

To get all the notes:

NoteModel.find({})

To get all the users:

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

To get all the problems:

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

To get all the notes of a user:

NotesModel.find({ user: USER_ID })

To search for notes by problems:

NotesModel.find({ problem: PROBLEM_ID })

Now, the above is how you do it in mongoose, now let's create a RESTFUL controller for all of that: (assuming you're using 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,
  })
}))

The req.query is what's going to include the search filters, the search filters will be sent by the client (the front-end) as follows:

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