很抱歉,如果这是一个 n00b 问题,我已经搜索 Google 和 Stack 几个小时了,我必须问!
我有两个模式,用户和故事,如下所示。我正在尝试使用 Ref 选项为 Story 引用 User 以在查询中填充 - 我之前使用过 mySQL,因此想尝试复制 JOIN 语句。每当我尝试使用填充时,我只会返回 objectID 或 null(如下所示)。
11 月 12 日编辑以修复硬编码 ID 并添加控制台数据
故事模式.js
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
User = require('./user-schema');
var StorySchema = new Schema({
title: { type: String, required: true },
author_id: { type: Schema.Types.ObjectId, ref: 'User' },
summary: { type: String, required: true },
rating: { type: String, required: true }
});
module.exports = mongoose.model('Story', StorySchema, 'stories');
用户模式.js
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var UserSchema = new Schema({
username: { type: String, required: true, index: { unique: true } },
is_admin: {type: Boolean, required: true, default: false }
});
保存 - 例如 id 硬编码
app.post('/api/new_story', function(req, res){
var story;
story = new Story({
title: req.body.title,
author_id: mongoose.Types.ObjectId(req.params._id),
/* ex of req.params._id: 527fc8ff241cdb8c09000003*/
summary: req.body.summary,
rating: req.body.rating
});
story.save(function(err) {
if (!err) {
return console.log("created");
} else {
return console.log(err);
}
});
return res.send(story);
});
登录终端时的示例用户
{
"__v" : 0,
"_id" : ObjectId("527fc8ff241cdb8c09000003"),
"is_admin" : false,
"username" : "ted"
}
登录终端时的示例故事
{
"title" : "Test Story",
"author_id" : "527fc8ff241cdb8c09000003",
"summary" : "Test summary",
"rating" : "12",
"_id" : ObjectId("52827692496c16070b000002"),
"__v" : 0
}
查询
//other mongoose/app includes above
User = require('./config/schema/user-model'),
Story = require('./config/schema/story-model');
// data.author_id = 527fc8ff241cdb8c09000003
// data.author_id.username = undefined
app.get('/api/query/:id', function (req, res){
return Story.findOne({_id:req.params.id})
.populate( { path: 'User' } )
.exec(function (err, data) {
console.log(data.author_id);
console.log(data.author_id.username);
if (err) {
return res.json({error:err})
}
})
});
// data.author_id = null
app.get('/api/query2/:id', function (req, res){
return Story.findOne({_id:req.params.id}) //_id hardcoded for example
.populate( 'author_id' )
.exec(function (err, data) {
console.log(data.author_id);
if (err) {
return res.json({error:err})
}
})
});
在第一个查询中,我得到了我已经保存回来的 author_id,这很有意义,因为这就是我保存的 - 但我访问了用户名。
在第二个查询中,我什至无法访问我已经保存的 author_id。
编辑:我可以在没有“填充”的情况下运行正常的 GET 查询
我希望发生的事情
就是能够从故事中获取作者信息——这更像是一个概念证明。最终,我想在 User 模型中引用 Story _id,因为一个用户可以有很多故事,但每个故事只有一个用户,但我想我会先从这里开始。