以下是我的架构
var mongoose = require("mongoose");
var messageSchema = mongoose.Schema({
text: { type: String, required: true },
author: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
name: { type: String, required: true }
}
});
module.exports = mongoose.model("Message", messageSchema);
我的用户架构
var mongoose = require("mongoose");
var passportLocalMongoose = require("passport-local-mongoose");
var uniqueValidator = require('mongoose-unique-validator');
var UserSchema = mongoose.Schema({
username: { type: String, required: true, unique: true },
password: { type: String, required: true },
first_name: { type: String, required: true },
middle_initial: { type: String, required: true },
last_name: { type: String, required: true },
phone: { type: Number, required: true },
address: { type: String, required: true },
email: { type: String, required: true, unique: true },
isManager: Boolean,
isSysAdmin: Boolean,
points_accrued: Number,
messages: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Message"
}
],
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
}
});
UserSchema.plugin(passportLocalMongoose);
UserSchema.plugin(uniqueValidator);
module.exports = mongoose.model("User", UserSchema);
然后这是我的路线
// Gets messages for regular Employees, not Admins
router.get("/messages", middleware.isLoggedIn, function (req, res) {
User.find({}).populate("message").exec(function (err, foundUsers) {
if (err || !foundUsers) {
req.flash("error", "Users Not Found");
res.redirect("back");
} else {
res.render("users/messages", { users: foundUsers });
}
});
})
//================//
// POST A MESSAGE //
//================//
router.post("/messages", middleware.isLoggedIn, function (req, res) {
User.findOne({ username: req.body.reciever }, (err, foundUser) => {
if (err) {
res.redirect("back")
} else {
const newMessage = {
text: req.body.message,
author: {
id: req.user._id,
name: req.user.first_name + " " + req.user.middle_initial + " " + req.user.last_name
}
}
Message.create(newMessage, (err, newMessage) => {
if (err) {
req.flash("error", "Whoops! Something went wrong...");
console.log(err);
res.redirect("/users/messages");
} else {
User.findOneAndUpdate({ username: req.body.reciever }, { $push: { messages: newMessage._id } }, (err, updateData) => {
req.flash("success", "Message Sent!");
res.redirect("/users/messages");
})
}
})
}
})
})
最后,这是我的ejs文件
<div class="container">
<% user.messages.forEach(function(message){ %>
<% console.log(message.author); %>
<p>
<%= message %>
</p>
<% }); %>
</div>
因此ID正在显示消息,但我无法访问作者信息或文本。 ejs文件中的console.log()返回undefined。我的数据库中的数据是正确的,并显示所有信息。我试过.populate({路径:&#34;消息&#34;}),但即使这样也行不通。谢谢!