在尝试联接两个文档时,无法在Mongoose中填充路径

c0vxltue  于 2022-11-13  发布在  Go
关注(0)|答案(2)|浏览(117)

Mongoose 错误:无法填充路径loaned_to,因为它不在您得架构中.请将strictPopulate选项设置为false以覆盖.

我尝试在nodejs中使用mongoose来连接mongodb中的两个文档,但不幸的是发生了这个错误。我的mongoose版本是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})
    }
}
bkkx9g8r

bkkx9g8r1#

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 });
  }
};
bqf10yzr

bqf10yzr2#

使用嵌套填充,如下例所示(该示例假定令牌模型具有一个用户,该用户通常具有一个角色,而该角色具有权限)。这将返回一个与筛选令牌关联的用户对象,以及分配给该用户的角色和分配给该角色的权限。
即:令牌模型(与之有关系)-〉用户模型(与之有关系)-〉角色模型(与之有关系)-〉权限模型)

const popObj = {
        path: 'user',
        options: { sort: { position: -1 } },
        populate: {
          path: 'role',
          select: 'name',
          populate: {
            path: 'permissions'
          }
        }
};
const tokenFilter = {is_active: true};
TokenModel.find(userFilter).populate(popObj);

相关问题