我有 2 个这样的模式:
var mongoose = require("mongoose");
var passportLocalMongoose = require("passport-local-mongoose");
var universitySchema = new mongoose.Schema({
name: String,
location: String,
image: String,
comments: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Comment"
}
]
});
module.exports = mongoose.model("University", universitySchema);
和
var mongoose = require("mongoose");
var passportLocalMongoose = require("passport-local-mongoose");
var commentSchema = new mongoose.Schema({
text: String,
createDate: {type: Date, default: Date.now},
author: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
username: String
}
});
module.exports = mongoose.model("Comment", commentSchema);
而且它工作正常,我可以添加评论并在数据库中检查; 评论和在大学中找到的ID都匹配。但是当我尝试做类似的事情时
university.comments[0].createDate
university.comments[0].username
university.comments[0].text
或在每个循环中comment.username comment.createDate
等。
它为用户提供了未定义的空字符串和我试图获取的其他详细信息的空字符串。它在我的另一个应用程序中运行良好,我不知道我在这里到底搞砸了什么。
Neil Lunn在评论中提供了解决方案:
大学从何而来?它是 .find() 还是 .findOne() 的结果?如果是 .find(),那么 university 本身就是一个数组。它也是一个"引用"架构。你叫 .populate() 吗?因为如果你没有,那么那里就没有对象,只有 ObjectId 值。另外,"添加评论"是什么意思?如果你想这样做,那么你通过评论模型而不是大学更新。所有这些问题的大量现有答案。