【问题标题】:Cannot dump or return relation array inside mongoose object无法在 mongoose 对象中转储或返回关系数组
【发布时间】: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


    【解决方案1】:

    为了能够使用虚拟填充,您需要将 toJSON: { virtuals: true } 选项添加到架构中。

    所以应该是这样的:

    userSchema = mongoose.Schema(
      {
        name: {
          type: String,
          required: true
        },
        email: {
          type: String,
          required: true,
          unique: true
        },
        password: {
          type: String,
          required: true
        }
      },
      {
        toJSON: { virtuals: true }
      }
    );
    

    来自docs

    请记住,虚拟不包含在 toJSON() 输出中 默认。如果您希望在使用函数时显示填充虚拟对象 依赖 JSON.stringify() 的,比如 Express 的 res.json() 函数,设置 virtuals: true 模式的 toJSON 选项上的选项。

    【讨论】:

      猜你喜欢
      • 2017-10-26
      • 2020-09-14
      • 2014-07-09
      • 2020-11-11
      • 2016-07-28
      • 1970-01-01
      • 2015-04-05
      • 1970-01-01
      • 2016-05-21
      相关资源
      最近更新 更多