【问题标题】:How to push an object created on mongoose to populate another schema如何推送在猫鼬上创建的对象以填充另一个模式
【发布时间】:2020-03-07 15:44:01
【问题描述】:

我在 MongoDb 上有两个模型,一个用于用户,另一个用于事件。用户创建帐户并登录后,它会显示受保护的页面,可以将事件添加到他们自己的个人资料中。我正在尝试使用 populate("events") 来引用事件架构以显示在用户架构上。还有 $push 在创建后将事件推送给用户。结果是:事件创建得很好,但是没有任何东西被推送到用户模型上的事件数组中。使用邮递员查看用户,它显示事件数组为空,我得到的响应是 200 和一个空对象。我在这里想念什么?这是我第一次在 MongoDb 上关联模式,但无法使其正常工作。非常感谢任何帮助。

我尝试在 { new: true } 之后添加回调函数,同样,{safe: true, upsert: true},但没有任何变化。

这是我的一些代码:

用户模型:

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const userSchema = new Schema({
  username: { type: String, required: true },
  firstName: { type: String, required: true },
  lastName: { type: String, required: true },
  phone: { type: String },
  password: { type: String },
  email: { type: String, required: true },
  events: [{ type: Schema.Types.ObjectId, ref: "Event" }]
});

const User = mongoose.model("User", userSchema);

module.exports = User;

事件模型:

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const eventSchema = new Schema({
  title: { type: String, required: true },
  start: { type: Date, required: true },
  end: { type: Date, required: true },
  appointment: { type: String, required: true }
});

const Event = mongoose.model("Event", eventSchema);

module.exports = Event;

创建事件的路由,然后尝试将创建的对象推送到用户的架构:

router.post("/users/:_id", function(req, res) {
  Event.create({
    title: req.body.title,
    start: req.body.start,
    end: req.body.end,
    appointment: req.body.appointment
  })
    .then(function(dbEvent) {
      return User.findOneAndUpdate(
        { _id: req.params._id },
        {
          $push: {
            events: dbEvent._id
          }
        },
        { new: true }
      );
    })
    .then(function(dbUser) {
      res.json(dbUser);
    })
    .catch(function(err) {
      res.json(err);
    });
});

获取一个用户,但它返回的用户是一个空的事件数组。

router.get("/users/:_id", (req, res) => {
  return User.findOne({
    _id: req.params._id
  })
    .populate("events")
    .then(function(dbUser) {
      if (typeof dbUser === "object") {
        res.json(dbUser);
      }
    });
});

提前致谢。

【问题讨论】:

  • 这一定行得通,除了一些代码组织之外,我认为您的代码没有问题。您确定要将现有用户 ID 发送到您的发布路线吗?像这样的东西:.../users/5dca71a2ba514706d0c7186b
  • 是的,我正在发送一个现有用户,我正在取回它,但事件数组是空的

标签: express mongoose populate


【解决方案1】:

问题是我在单独的文件中有事件路由和用户路由,我忘记将用户模型导入事件路由: const User = require("../../models").User;

【讨论】:

    猜你喜欢
    • 2013-01-13
    • 2021-04-17
    • 1970-01-01
    • 2014-07-24
    • 2021-04-24
    • 2018-10-15
    • 2020-11-24
    • 2020-08-15
    • 2021-09-19
    相关资源
    最近更新 更多