【发布时间】:2018-04-15 16:26:22
【问题描述】:
我有 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);
它工作正常,我可以添加 cmets 并在数据库中检查;在大学匹配中找到的评论和 id。但是当我尝试做类似的事情时
university.comments[0].createDate
university.comments[0].username
university.comments[0].text
或 while 在每个循环中 comment.username comment.createDate 等
它为我提供了未定义的用户和空字符串以获取我想要获取的其他详细信息。它在我的其他应用程序中运行良好,我不知道我到底在这里搞砸了什么。
【问题讨论】:
-
university来自哪里?是.find()还是.findOne()的结果?如果是.find(),那么university本身就是Array。它也是一个“引用”模式。你打电话给.populate()了吗?因为如果你没有,那么那里就没有对象,只有ObjectId值。还有“添加 cmets”是什么意思?如果你想这样做,那么你通过Comments模型而不是university进行更新。所有这些问题的大量现有答案。 -
我认为你是对的,这是人口问题,该死的我又被它咬了
-
是的!确认的!我是个智障谢谢!
标签: javascript database mongoose mongoose-schema