我有2种模式:
const mongoose = require('mongoose');
const PinSchema = new mongoose.Schema({
title: String,
content: String,
image: String,
latitude: Number,
longitude: Number,
author: {
type: mongoose.Schema.ObjectId,
ref: "User"
},
comments: [
{
text: String,
createdAt: {
type: Date,
default: Date.now,
author: {
type: mongoose.Schema.ObjectId,
ref: "User"
}
}
}
]
}, { timestamps: true });
module.exports = mongoose.model("Pin", PinSchema);
和
const mongoose = require('mongoose');
const UserSchema = new mongoose.Schema({
name: String,
email: String,
picture: String
});
module.exports = mongoose.model("User", UserSchema);
如您所见,Pin中的author
字段与User模式中的_id
相同。
然后我尝试像这样在Pin模式中填充注释author
字段:
const pinUpdated = await Pin.findOneAndUpdate(
{ _id: pinId },
{ $push: { comments: "some comment" } },
{ new: true }
).populate("author")
.populate("comments.author");
但是结果对象的author
字段设置为null
,因此填充无效。
我不反对使用$lookup
使用本机mongo语法来执行此操作,但在我的情况下,它不仅查找数组,还查找对象数组的字段:
db.pins.aggregate([
{
$lookup:
{
from: "users",
localField: "comments._id", // this won't work
foreignField: "_id",
as: "authorOutput"
}
}
])
populate()
中我缺少什么?
答案 0 :(得分:1)
似乎您在author
数组中的comments
字段嵌套在createdAt
对象中,这可能是无意的。将PinSchema
更改为以下内容(在作者之前关闭花括号)应该可以解决此问题:
const PinSchema = new mongoose.Schema({
...
comments: [
{
text: String,
createdAt: {
type: Date,
default: Date.now,
},
author: {
type: mongoose.Schema.ObjectId,
ref: "User"
}
}
]
}, { timestamps: true });