user15324999
user15324999

Reputation: 81

node js find collection array specific value

Hi guys currently im working on some notification system and i did solve this but after some change i lost my previous code and now i cant reach the result here:

model

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const notificationSchema = new Schema({
    type: { type: Number, required: true },
    recipients: { type: Array, required: true , Ref: 'User'},
    unreaded: { type: Array, required: true , Ref: 'User'},
    value_1: { type: String },
    value_2: { type: String },
    date: { type: String, required: true }
});

module.exports = mongoose.model('Notification', notificationSchema);

controller:

const getNotifications = async (req, res, next) => {
  const userId = req.params.uid;

  let notifications;
  try {
    notifications = await Notification.find({recipients: userId});
  } catch (err){}

  if (!notifications) {
    const error = new HttpError('backend_message3', 404);
    return next(error);
  }

  return res.json({ notifications  });
};

And this is my result in mongodb collections I will provide a photo here:click for image

I tried so much examples here, and I know when I did this first time the example was so simple but now i cant figure out how.

Also one more question is it good to use socket.io with setinterval, because can it make some errors in server?

Upvotes: 1

Views: 41

Answers (1)

Dheemanth Bhat
Dheemanth Bhat

Reputation: 4452

Try changing your notificationSchema to this:

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

const notificationSchema = new Schema({
  type: { type: Number, required: true },
  recipients: [{ type: Schema.Types.ObjectId, ref: 'User' }],
  unreaded: [{ type: Schema.Types.ObjectId, ref: 'User' }],
  value_1: { type: String },
  value_2: { type: String },
  date: { type: String, required: true }
});

module.exports = mongoose.model('Notification', notificationSchema);

Upvotes: 1

Related Questions