【发布时间】: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