尝试加入两个文档时无法在 Mongoose 中填充路径

Posted

技术标签:

【中文标题】尝试加入两个文档时无法在 Mongoose 中填充路径【英文标题】:Cannot Populate path in Mongoose while trying to join two documents 【发布时间】:2021-11-14 22:56:10 【问题描述】:

MongooseError: 无法填充路径 loaned_to,因为它不在您的架构中。将 strictPopulate 选项设置为 false 以覆盖。

我尝试在nodejs中使用mongoose在mongodb中加入两个文档,但不幸的是出现了这个错误。我的猫鼬版本是6.0.6

图书架构

const mongoose = require('mongoose');

const BookSchema = new mongoose.Schema(
    "name": type: String, required: true,
    "author_name": type: String, required: true,
    "published_date": type: Date, required: false,
    "copies": [
        
            "isbn_number": type: String, required: true,
            "status": type: String, required: true, default: "Available",
            "due_back": type: Date, required: false,
            "loaned_to": type: mongoose.Schema.Types.ObjectId, required: false, ref: "User"
        ,
    ]
)

const Book = mongoose.model("Book", BookSchema);
module.exports = Book;

用户架构

const mongoose = require('mongoose');

const UserSchema = new mongoose.Schema(
    "first_name": type: String, required: true,
    "last_name": type: String, required: true,
    "phone_number": type:  String, required: true,
    "address": type:  String, required: false,
    "user_name":type: String, required: true,
    "password": type:  String, required: true,
    "email": type:  String, required: true,
    "notifications": [
        
            "notification_id" : type:"string", required:true,
            "notification": type: "string", required: true
        ,
    ]
)

const User = mongoose.model("User", UserSchema);
module.exports = User;

我的加入文档的代码

exports.getAllBooks = async (req, res) => 
    try 
        let data = await BookModel.findOne().populate("loaned_to");
        res.status(200).send(data: [...data], success: true)
     catch (err) 
        console.log(err)
        res.status(404).send(success: false, msg: err.message)
    

【问题讨论】:

【参考方案1】:
exports.getAllBooks = async (req, res) => 
  try 
    let data = await BookModel.findOne().populate(
      path: 'copies.loaned_to',
      select:
        'first_name lastName phone_number address user_name email notifications',
    );
    res.status(200).json( data: [...data], success: true );
   catch (err) 
    console.log(err);
    res.status(500).json( success: false, msg: err.message );
  
;

【讨论】:

非常感谢兄弟,我花了很多时间来调试这个? 不客气? 出了什么问题? @randomuser 问题是将数据填充到副本中。loaned_to

以上是关于尝试加入两个文档时无法在 Mongoose 中填充路径的主要内容,如果未能解决你的问题,请参考以下文章

对 mongoose 3.x 填充文档进行排序的正确语法

Mongoose 从另一个子文档填充子文档,其中两个子文档都是主文档的一部分

Mongoose - 无法在路径 notification.from 上使用排序填充,因为它是文档数组的子属性

为啥在 mongoose 中需要 execPopulate 方法来填充现有文档?

为啥在 mongoose 中需要 execPopulate 方法来填充现有文档?

使用 Typescript mongoose 填充的 expressjs