如何填充ObjectIDS数组的每个条目?

时间:2019-07-27 21:11:08

标签: node.js mongoose mongoose-populate

我正在填充一个ObjectIds数组。我要去哪里错了?

我尝试引用此内容,但找不到解决我问题的方法。 Mongoose - accessing nested object with .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);
    });
});

eventsNotifications模式:

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

clientSchema:

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

我期望所有eventsNotifications的数组:

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

但是,如果我尝试console.log(foundClient.eventsNotifications [0] .notification),则会收到一个空数组,这意味着未填充eventsNotifications数组。

实际上,我什至不想在键上进行.notification,.read等操作,我想返回整个对象数组。

1 个答案:

答案 0 :(得分:0)

在.populate函数.populate("EventsNotifications")中, 必须提到包含ObjectId的字段的名称。

因此,我将其更改为.populate("eventsNotifications") 而且有效。