【问题标题】:How to populate each entry of an array of ObjectIDS?如何填充 ObjectIDS 数组的每个条目?
【发布时间】:2019-12-05 17:55:43
【问题描述】:

我正在填充一个 ObjectId 数组。我哪里错了?

我试图参考这个,但找不到我的问题的解决方案。 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 数组没有被填充。

其实我什至不想在keys上做.notification、.read之类的东西,我想返回整个对象数组。

【问题讨论】:

    标签: node.js mongoose mongoose-populate


    【解决方案1】:

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

    所以,我只是将其更改为.populate("eventsNotifications") 并且成功了。

    【讨论】:

      猜你喜欢
      • 2020-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-25
      • 2018-11-16
      • 2021-03-12
      相关资源
      最近更新 更多