在 jNode 中进行正确的对象引用但数据检索无效(使用 mongoose)
Doing correct object referencing in jNode but having invalid data retrieval (using mongoose)
我有 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
或在 for each 循环中 while comment.username comment.createDate
等
它为用户提供了未定义的信息,为我试图获取的其他详细信息提供了空字符串。它在我的其他应用程序中运行良好,我不知道我到底搞砸了什么。
Neil Lunn 在评论中提供了解决方案:
Where is university coming from? Is it the result of .find() or .findOne()? If it's .find() then university is an Array itself. It's also a "referenced" schema. Did you call .populate()? Because if you did not then there is no object there, and just ObjectId values. Also what does "add comments" mean? If you want to do that then you update via the Comments model and not university. Plenty of existing answers for all of those issues.
我有 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
或在 for each 循环中 while comment.username comment.createDate
等
它为用户提供了未定义的信息,为我试图获取的其他详细信息提供了空字符串。它在我的其他应用程序中运行良好,我不知道我到底搞砸了什么。
Neil Lunn 在评论中提供了解决方案:
Where is university coming from? Is it the result of .find() or .findOne()? If it's .find() then university is an Array itself. It's also a "referenced" schema. Did you call .populate()? Because if you did not then there is no object there, and just ObjectId values. Also what does "add comments" mean? If you want to do that then you update via the Comments model and not university. Plenty of existing answers for all of those issues.