【发布时间】:2020-06-15 12:35:16
【问题描述】:
我正在尝试使用 Node 和 Express 学习与 MongoDB 和 mongoose 的基本关系。
用户模型
let mongoose = require("mongoose");
userSchema = mongoose.Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
}
});
userSchema.virtual("posts", {
ref: "Post",
localField: "_id",
foreignField: "userId"
});
// Making sure that password field is not present in responses
userSchema.methods.toJSON = function() {
let user = this.toObject();
delete user.password;
// console.log(user.posts);
return user;
};
// Creating model from schema
User = mongoose.model("User", userSchema);
module.exports = User;
后模型
let mongoose = require("mongoose");
postSchema = mongoose.Schema({
body: {
type: String,
required: true
},
userId: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: "User"
}
});
let Post = mongoose.model("Post", postSchema);
module.exports = Post;
这是我正在使用的两个模型。用户有很多帖子。
现在我知道我可以通过以下方式获得一位用户:
let user = await User.findOne();
我可以通过以下方式填充帖子关系:
await user.populate("posts").execPopulate();
但是当我console.log(user) 或res.send(user) 时,我只看到用户数据,看不到帖子关系数据。我可以console.log(user.posts) 并以这种方式获取数据。但是为什么它不与对象本身一起出现呢?这是默认行为吗?如果是,如何在我的响应中获取带有帖子数组的用户对象?
【问题讨论】:
标签: node.js mongodb express mongoose