Mongoose Model不保存引用的模型?

时间:2018-06-02 11:32:16

标签: javascript node.js database mongodb mongoose

我目前正在尝试使用mongo和express设置后端API,我正在努力让创建路由工作。这是我的路线:

reservationsRouter.post("/", (req, res) => {
  assert.notEqual(req.body.user, null);
  const user = User.findById(req.body.user);
  const reservation = new Reservation({
    dateStart: req.body.dateStart,
    dateEnd: req.body.dateEnd,
    user: user
  });
  res.json(reservation);
  reservation.save();
});

我的预订解答:

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

const ReservationSchema = Schema({
  user: { type: Schema.ObjectId, ref: "User", required: true },
  dateStart: { type: String, required: true },
  dateEnd: { type: String, required: true }
});

module.exports = ReservationSchema;

和我的userSchema:

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

const userSchema = Schema({
  _id: { type: String, required: true },
  firstName: { type: String, required: true },
  lastName: { type: String, required: true },
  reservations: [{ type: Schema.Types.ObjectId, ref: "Reservation" }]
});

module.exports = userSchema;

我的问题是,当我保存预订并获取所有预订时,它没有user属性,即使我已在模式中指定它:

{
    "dateStart": "1234",
    "dateEnd": "12345",
    "_id": "5b127d9d3d8256eedd31173b"
}

编辑:我已按如下方式重写路线,以便回叫与用户一起返回预订,但是,当我获取所有预订时,不包括用户,如上例所示

reservationsRouter.post("/", (req, res) => {
  assert.notEqual(req.body.user, null);
  const user = User.findById(req.body.user, (err, user) => {
    if (err) res.send(err);
    else {
      const reservation = new Reservation({
        dateStart: req.body.dateStart,
        dateEnd: req.body.dateEnd,
        user: user
      });
      res.json(reservation);
      reservation.save();
    }
  });
});

您可能需要查看整个仓库:https://github.com/SchulenbergOrg/backend/tree/mongo

0 个答案:

没有答案