【发布时间】:2020-06-07 22:55:38
【问题描述】:
所以我有这个引用博客的用户模型
用户模型
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const bcrypt = require("bcryptjs");
const userSchema = new Schema(
{
email: {
type: String,
required: true,
index: {
unique: true
}
},
password: {
type: String,
required: true
},
name: {
type: String,
required: true
},
website: {
type: String
},
bio: {
type: String
},
blogs: [
{
type: Schema.Types.ObjectId,
ref: "Blog"
}
]
},
{
timestamps: {
createdAt: "created_at",
updatedAt: "updated_at"
}
}
);
userSchema.pre("save", function(next) {
const user = this;
if (!user.isModified("password")) return next();
bcrypt.genSalt(10, function(err, salt) {
if (err) return next(err);
bcrypt.hash(user.password, salt, function(err, hash) {
if (err) return next(err);
user.password = hash;
next();
});
});
});
userSchema.methods.comparePassword = function(password, next) {
bcrypt.compare(password, this.password, function(err, isMatch) {
if (err) return next(err);
next(null, isMatch);
});
};
const User = mongoose.model("User", userSchema);
module.exports = User;
这是我的博客集合,其中引用了 cmets 模型
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const blogSchema = new Schema(
{
title: {
type: String,
required: true
},
body: {
type: String,
required: true
},
author: {
type: Schema.Types.ObjectId,
ref: "User"
},
likesCount: {
type: Number
},
comments: [
{
type: Schema.Types.ObjectId,
ref: "Comment"
}
]
},
{
timestamps: {
createdAt: "created_at",
updatedAt: "updated_at"
}
}
);
const Blog = mongoose.model("Blog", blogSchema);
module.exports = Blog;
这是我的 cmets 模型,它引用了用户模型
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const CommentSchema = new Schema(
{
body: {
type: String,
required: true
},
likesCount: {
type: Number
},
user: {
type: Schema.Types.ObjectId,
ref: "User"
}
},
{
timestamps: {
createdAt: "created_at",
updatedAt: "updated_at"
}
}
);
const Comment = mongoose.model("Comment", CommentSchema);
module.exports = Comment;
我想要的是如果我获取用户数据我想获取博客以及评论数据 我有这个代码
exports.getCurrentUser = async (req, res) => {
const ObjectId = mongoose.Types.ObjectId;
const users = await User.findById({ _id: new ObjectId(req.user._id) })
.populate({
path: "blogs",
model: "Blog"
})
.exec();
console.log(users);
return res.status(200).json(users);
};
但它没有填充博客
如何实现这种嵌套引用获取?
【问题讨论】:
标签: node.js mongodb mongoose nosql