javascript - 为什么 mongoose populate 在填充数组时不起作用?

标签 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 字段与用户架构中的 _id 相同。

然后,我尝试填充 Pin 架构中的注释 author 字段,如下所示:

const pinUpdated = await Pin.findOneAndUpdate(
        { _id: pinId },
        { $push: { comments: "some comment" } },
        { new: true }
      ).populate("author")
       .populate("comments.author");

但是结果对象的 author 字段设置为 null,因此总体不起作用。

我并不反对使用 $lookup 使用 native mongo 语法执行此操作,但就我而言,它不仅仅是查找数组,而是查找对象数组的字段:

db.pins.aggregate([
    {
   $lookup:
     {
       from: "users",
       localField: "comments._id", // this won't work
       foreignField: "_id",
       as: "authorOutput"
     }
}    
])

我在populate()中缺少什么?

最佳答案

看起来 comments 数组中的 author 字段嵌套在 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 });

关于javascript - 为什么 mongoose populate 在填充数组时不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58029873/

相关文章:

javascript - Mongoose 属性过滤器

javascript - Mongoose 错误: `{"message":"No matching document found." ,"name" :"VersionError"}`

javascript - 有没有一种实用的方法可以在 Production 中添加 Webpack 生成的样式表

javascript - 如何使用 React-leaflet v3 在 map 加载时将 map 设置为地理位置

python - 在没有迭代的情况下将字典批量存储在redis中

mongodb - robomongo aws ec2 ubuntu

javascript - 在 React Native 中创建一个 Theme Provider 组件

javascript - 如何使用 t-extend 添加新按钮?

ruby-on-rails - RubyMine 上的 MongoDB 支持

javascript - MongoDB 查询可以工作,但不能与 Mongoose 一起使用