猫鼬的populate()不从数据库返回数据

时间:2018-09-05 04:05:08

标签: node.js mongodb reactjs mongoose

我有以下模式,而Base是信息的一对一收集器:

const BaseSchema = mongoose.Schema({
  creatorId: { type: mongoose.Schema.Types.ObjectId, required: true },
  title: { type: String, required: true },
  created: { type: Date, default: Date.now() },
  users: [{ type: mongoose.Schema.Types.ObjectId, ref: "User" }],
  messages: [{ type: mongoose.Schema.Types.ObjectId, ref: "Message" }]
});

并且:

const BaseUserSchema = mongoose.Schema({
  userId: { type: String },
  baseId: { type: mongoose.Schema.Types.ObjectId },
  created: { type: Date, default: Date.now() },
  acceptedMembership: { type: Boolean, default: false },
  isCreator: { type: Boolean, default: false }
});

(我有一个Message,看起来差不多) 后者在User中称为const User = mongoose.model("User", UserSchema); 创建新的基准站时,我会自动将用户添加到其中的列表中。在数据库中,我可以看到该用户确实存在,但是当我调用以下命令时,该字段并未填充:

Base.find({ creatorId: req.params.id })
    .populate("users", "messages")
    .exec()
    .then(data => console.log(data));

我从console.log中获得以下内容:

[ { created: 2018-09-05T03:41:45.416Z,
    users: [],
    messages: [],
    _id: 5b8f508b2760c5329c13a9be,
    creatorId: 5b86f7970cd98b2004969bf0,
    title: 'testBase1',
    __v: 1 } ]

当我第一次通过React前端创建基础并将基础添加到列表中时,我看到users.length为1,即自动创建的用户的长度。但是,当我刷新页面时,控制台中的用户列表为空。

添加: 忘记显示创建后如何填充用户列表:

router.post("/add", jwtAuth, (req, res) => {
    Base.create({
        creatorId: req.body.userId,
        title: req.body.title
    }).then(baseInfo => {
        BaseUser.create({
            userId: req.body.username,
            baseId: baseInfo._id,
            created: Date.now(),
            acceptedMembership: true,
            isCreator: true
        })
            .then(baseuser => {
                baseInfo.users.push(baseuser);
                return baseInfo.save();
            })
            .then(base => res.json(base.serialize()));
    });
});

1 个答案:

答案 0 :(得分:0)

答案

.populate("users", "messages")

首先将从messages返回users。它必须是两个单独的条目,例如:

        .populate("users")
        .populate("messages")

然后,在模型中

users: [{ type: mongoose.Schema.Types.ObjectId, ref: "User" }],

表示错误的ref。必须是

users: [{ type: mongoose.Schema.Types.ObjectId, ref: "BaseUser" }],

来自

const BaseUser = mongoose.model("BaseUser", BaseUserSchema);

最后,我不确定是否需要这样做,但是我向每个要填充的项目中添加了ref

baseId: { type: mongoose.Schema.Types.ObjectId, required: true, ref: "Base" },
baseId: { type: mongoose.Schema.Types.ObjectId, ref: "Base" },

现在,它像一个咒语一样工作,所有这些都无需附加fetch