为什么在填充数组时猫鼬填充不起作用?

时间:2019-09-20 14:01:11

标签: javascript mongodb mongoose

我有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()中我缺少什么?

1 个答案:

答案 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 });