猫鼬填充不适用于嵌套对象

时间:2019-10-22 13:02:23

标签: node.js mongodb express mongoose

Client.js

const mongoose = require("mongoose");
var Schema = mongoose.Schema;
const clientSchema = new mongoose.Schema(
    {
        name: { type: String, required: true, default: "" },
    }, {
        timestamps: true
    }
);
module.exports = mongoose.model("Client", clientSchema);

User.js

const mongoose = require("mongoose");
var Schema = mongoose.Schema;
const userSchema = new mongoose.Schema({
        name: { type: String, required: true, default: "" },
        clients: [{
                client: {
                    type: Schema.Types.ObjectId,
                    ref: "Client",
                    default: null
                },
                user_group: {
                    type: Number
                    default: null
                }
            }]
    }, { timestamps: true });
module.exports = mongoose.model("User", userSchema);

auth.js(尝试填充客户端的地方)

const express = require("express");
const router = express.Router();
const User = require("../models/User");
const Client = require("../models/Client");
router.post("/users", (req, res) => {
    let params = req.body;
    let total_client = [];
    User.findOne({
        email: params.email
    })
    .populate({
         path: "clients.client",
         model: Client
      })
      .exec((err, user) => {
          console.log(user);
          res.send(user);
       });
});
module.exports = router;

请检查上面的代码。我已经给出了两个模型user.js和client.js的代码示例。在用户架构中,我在数组对象内引用了client。查询用户时,客户端不填充。请帮我把事情做好。提前致谢。

2 个答案:

答案 0 :(得分:0)

以下内容希望您在帖子请求的json正文中提供一个名称(您的示例使用的是用户模型中不存在的电子邮件)。另外,您的模型已经在定义ref:Client,因此您可以简化请求,仅包括路径clients.client

router.post("/users", async (req, res) => {
    const { name } = req.body;
    const user = await User.findOne({ name: name }).populate('clients.client').exec();
    res.send(user);
});

答案 1 :(得分:0)

解决了此问题,仅在client.js文件的模块导出中添加了一个额外的参数

module.exports = mongoose.model("Client", clientSchema, "client");