Search code examples
node.jsmongodbexpressmongoosemongoose-schema

Saving an item that is specific to a user schema but not able to retrieve it back - mongoose


  • I have creared two schemas, user and medicine.
  • If a user adds medicines it should show up only in his/her account.
  • I am able to save the medicine ids to that specific user but i'm not able to get those medicines back i.e: medicines show for all the other users as well.

Here's the code snippet that saves meds to specific user:

const {userId, medName, medDescription, dose, medType, date, time} = req.body;
  try {
    const newMed = new MedsSchema({
      userId,
      medName,
      medDescription,
      dose,
      medType,
      date,
      time,
    });
    await newMed.save().then(() => res.send({response: 'ok'}));

    const specificUser = await User.findById({_id: userId});
    specificUser.medicines.push(newMed);
    await specificUser.save().then(
      User.findOne(specificUser)
        .populate('medicines')
        .exec(function (err, docs) {
          if (err) return handleError(err);
          console.log(docs);
        }),
    );

Here's the userSchema:

const userSchema = new mongoose.Schema(
  {
    username: {
      type: String,
      required: true,
      unique: true,
    },
    password: {
      type: String,
      required: true,
    },
    phone: {
      type: Number,
      required: true,
    },
    email: {
      type: String,
      unique: true,
      required: true,
    },
    medicines: [{type: mongoose.Schema.Types.ObjectId, ref: 'MedsSchema'}],
  },
  {
    toJSON: {
      virtuals: true,
    },
  },
);
router.get('/getMeds/:Id', (req, res) => {
  console.log(req.params.Id);
  MedsSchema.find({userId: req.params.Id}, function (err, result) {
    if (err) {
      res.send(err);
    } else {
      res.send(result);
    }
  });
});

what do i add to this that will make me get only specific medicines for that specific user instead of getting all medicines?


Solution

  • Can you edit your first code snippet to

    const { userId, medName, medDescription, dose, medType, date, time } = req.body;
    try {
      const user = await User.findOone({ _id: userId });
      const newMed = await MedsSchema.create({
        userId: user,
        medName,
        medDescription,
        dose,
        medType,
        date,
        time,
      });
    
      const specificUser = await User.findByIdAndUpdate({ _id: userId }, { $push: { medecines: newMed } });
      return res.json({ newMed, specificUser })
    };
    

    and in the router

    router.get('/getMeds/:Id', async (req, res) => {
      console.log(req.params.Id);
      const user = await User.findOne({ _id: req.params.Id }).populate({ path: 'medicines' })
      console.log(user.medicines)
      return res.json({meds: user.medicines})
    });
    

    also check the console results to see if everything is working