非常简单的填充过程,只是缺少一些简单的东西。我很茫然。使用NodeJS,Mongoose进行简单的React事情...
用户模型
const Schema = mongoose.Schema;
const UserSchema = new Schema({
email: {
type: String,
},
password: {
type: String,
},
books: [
{
type: Schema.Types.ObjectId,
ref: "Books"
}
]
});
module.exports.User = mongoose.model("User", UserSchema);
图书模型
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const BooksSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: "User"
},
title: {
type: String
},
author: {
type: String
},
description: {
type: String
}
});
module.exports.Books = mongoose.model("Books", BooksSchema);
函数调用
router.get("/test", (req, res) => {
User.find()
.populate("books")
.exec()
.then(user => {
res.json(user);
});
});
与我实际所做的相比,这是一个简化的概念。我以为我能理解,但显然不是。
当前,我有一个拥有两本书的用户(A)。我相信当我在Postman中运行这条路线时,应该会收到电子邮件,密码,ID和一堆书ID……或者,我想。请让我知道我做错了什么,或者给我一个简单的解释...谢谢...
答案 0 :(得分:0)
您应该只导出模式:
module.exports = mongoose.model("User", UserSchema);
module.exports = mongoose.model("Book", BookSchema); // Notice here "Book"
然后,当您进行查找时,请确保使用模式的确切名称:
router.get("/test", (req, res) => {
User.find()
.populate("books")
.exec()
.then(user => {
res.json(user);
});
});
我创建了您的模型/方案并进行了测试。让我知道您是否有任何问题。
答案 1 :(得分:0)
const Schema = mongoose.Schema;
const UserSchema = new Schema({
email: {
type: String,
},
password: {
type: String,
},
books: [
{
type: [Schema.Types.ObjectId],//you have to make this array of ids
ref: "Books"
}
]
});
module.exports.User = mongoose.model("User", UserSchema);
图书模型
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const BooksSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: "User"
},
title: {
type: String
},
author: {
type: String
},
description: {
type: String
}
});
module.exports.Books = mongoose.model("Books", BooksSchema);
Function call
router.get("/test", (req, res) => {
User.find()
.populate({path:"books",model:"Books"})
.exec()
.then(user => {
res.json(user);
});
});