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})
}
}
2条答案
按热度按时间bkkx9g8r1#
bqf10yzr2#
使用嵌套填充,如下例所示(该示例假定令牌模型具有一个用户,该用户通常具有一个角色,而该角色具有权限)。这将返回一个与筛选令牌关联的用户对象,以及分配给该用户的角色和分配给该角色的权限。
即:令牌模型(与之有关系)-〉用户模型(与之有关系)-〉角色模型(与之有关系)-〉权限模型)