Node.js 无法在mongoose对象内转储或返回关系数组
我正在尝试使用Node和Express学习与MongoDB和mongoose的基本关系 用户模型Node.js 无法在mongoose对象内转储或返回关系数组,node.js,mongodb,express,mongoose,Node.js,Mongodb,Express,Mongoose,我正在尝试使用Node和Express学习与MongoDB和mongoose的基本关系 用户模型 let mongoose = require("mongoose"); userSchema = mongoose.Schema({ name: { type: String, required: true }, email: { type: String, required: true, un
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 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=wait user.findOne()代码>
我可以通过以下方式填充posts关系:
wait user.populate(“posts”).execPopulate()代码>
但是当我console.log(user)
或res.send(user)
时,我只看到用户数据,没有看到posts关系数据。我可以console.log(user.posts)
这样获取数据。但是为什么它不会与对象本身一起出现呢?这是默认行为吗?如果是,我如何在我的响应中获取带有posts数组的用户对象?要能够使用虚拟填充,您需要向模式添加toJSON:{virtuals:true}
选项
所以它应该是这样的:
userSchema=mongoose.Schema(
{
姓名:{
类型:字符串,
必填项:true
},
电邮:{
类型:字符串,
要求:正确,
独一无二:真的
},
密码:{
类型:字符串,
必填项:true
}
},
{
toJSON:{virtuals:true}
}
);
从:
请记住,虚拟对象不包括在toJSON()输出中
违约如果您想在使用函数时显示填充虚拟对象
依赖于JSON.stringify()的函数,如Express'res.JSON()函数
模式的toJSON选项上的virtuals:true选项