Как заполнить каждую запись массива ObjectIDS?

Я заполняю массив ObjectIds. Где я ошибаюсь?

Я пытался сослаться на это, но не смог найти решение своей проблемы. Mongoose — доступ к вложенному объекту с помощью .populate

Код, выполняющий .populate:

router.get("/event", (req, res) => {
  Client.findById(req.params.client_id)
  .populate("EventsNotifications")
    .then(foundClient => {
      res.json(foundClient.eventsNotifications);
    })
    .catch(err => {
      console.log(`error from get event notifications`);
      res.json(err);
    });
});

Схема EventNotifications:

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

const eventNotificationSchema = new Schema({

    notification: {
        type: String,
    },
    read: {
        type: Boolean,
        default: false,
    }

}, {timestamps: true});

module.exports = mongoose.model("EventNotification",eventNotificationSchema);

Схема клиента:

const mongoose = require("mongoose"),
  Schema = mongoose.Schema,
  ObjectId = Schema.Types.ObjectId;

var validatePhone = function(contact) {
  var re = /^\d{10}$/;
  return contact == null || re.test(contact);
};

const clientSchema = new Schema({
  firstName: {
    type: String,
    required: true,
    minlength: 2
  },
  lastName: {
    type: String,
    required: false,
    minlength: 2
  },
  email: {
    type: String,
    required: true,
    match: [
      /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/,
      "Please fill a valid email address"
    ]
  },
  contact: {
    type: Number,
    required: true,
    validate: [validatePhone, "Please fill a valid phone number"]
  },
  eventsNotifications: [
    {
      type: ObjectId,
      ref: "EventNotification"
    }
  ]
});

module.exports = mongoose.model("Client", clientSchema);

Я ожидаю массив всех EventNotifications :

[{
"_id":"5d3c8d54126b9354988faf27",
"notification":"abdefgh",
"read":true
},
{"_id":"5d3c8d54126b9354988faf23",
"notification":"abdefgh",
"read":true
}
]

Но я получаю пустой массив, если пытаюсь выполнить console.log(foundClient.eventsNotifications[0].notification), это означает, что массив eventsNotifications не заполняется.

На самом деле, я даже не хочу делать .notification, .read и т. д. с ключами, я хочу вернуть весь массив объектов.


person fight_club    schedule 27.07.2019    source источник


Ответы (1)


В функции .populate .populate("EventsNotifications") должно быть указано имя поля, которое содержит ObjectId.

Итак, я просто изменил его на .populate("eventsNotifications"), и это сработало.

person fight_club    schedule 28.07.2019