Express 如何推动在mongoose上创建的对象来填充另一个模式
我在MongoDb上有两个模型,一个用于用户,另一个用于事件。用户创建帐户并登录后,将显示受保护的页面,在该页面中可以将事件添加到他们自己的配置文件中。我试图使用“填充”(“事件”)来引用要在用户模式上显示的事件模式。还有$push,用于在创建事件后将事件推送到用户。结果是:事件创建得很好,但没有任何内容被推送到用户模型上的事件数组中。使用postman查看用户,它显示事件数组为空,我得到的响应是200,其中有一个空对象。我错过了什么?这是我第一次在MongoDb上关联模式,无法让它工作。非常感谢您的帮助 我尝试在{new:true}之后添加一个回调函数,{safe:true,upsert:true},但没有任何变化 以下是我的一些代码: 用户模型:Express 如何推动在mongoose上创建的对象来填充另一个模式,express,mongoose,populate,Express,Mongoose,Populate,我在MongoDb上有两个模型,一个用于用户,另一个用于事件。用户创建帐户并登录后,将显示受保护的页面,在该页面中可以将事件添加到他们自己的配置文件中。我试图使用“填充”(“事件”)来引用要在用户模式上显示的事件模式。还有$push,用于在创建事件后将事件推送到用户。结果是:事件创建得很好,但没有任何内容被推送到用户模型上的事件数组中。使用postman查看用户,它显示事件数组为空,我得到的响应是200,其中有一个空对象。我错过了什么?这是我第一次在MongoDb上关联模式,无法让它工作。非常感
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);
}
});
});
提前感谢。问题是我在单独的文件中有事件路由和用户路由,并且我忘记了将用户模型导入事件路由:
const User=require(“../../models”).User 这一定是工作,我认为你的代码没有问题,除了一些代码组织。是否确实要将现有用户id发送到投递路线?类似这样的内容:…/users/5dca71a2ba514706d0c7186是的,我正在发送一个现有用户,并将其取回,但事件数组为空