Mongoose填充返回null或undefined

对不起,如果这是一个问题,我已经search了Google&Stack几个小时,现在我得问了!

我有两个模式,用户和故事,如下所示。 我想引用用户的故事使用Ref选项填充查询 – 我以前使用mySQL,所以想要尝试复制JOIN语句。 每当我尝试使用填充,我只是得到objectID返回,或null(如下所示)。

编辑11月12日修复硬编码的ID和添加控制台数据

故事schema.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'); 

用户schema.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 } }); 

例如,save – 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); }); 

用户loginterminal时的示例用户

 { "__v" : 0, "_id" : ObjectId("527fc8ff241cdb8c09000003"), "is_admin" : false, "username" : "ted" } 

loginterminal时的示例故事

 { "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查询没有“填充”

我想要发生什么

能够从故事中获取作者信息 – 这更像是一个概念certificate。 最终,我想引用用户模型中的Story _id,因为可能有许多故事给用户,但每个故事只有一个用户,但是以为我会先从这里开始。

由于你的例子包含了甚至没有被引用的有效的javascriptstring的原始对象ID,所以很难理解你的问题和你的代码中的错误是什么错误,但是大多数情况下你的第二个查询看起来应该起作用。 我怀疑你正在混合你的ObjectId值。 你正在为你的故事和你的用户使用相同的ObjectId,这是行不通的:

  author_id: mongoose.Types.ObjectId(528149b38da5b85003000002), 

这是您用来查找故事的相同ID。 所以我认为这个问题是:

  1. 确保在用户集合中有一个有效的用户logging
  2. 确保你的testing故事logging的story.author_id匹配
  3. 确保你正在通过故事Id查找故事,而不是author_id。

如果你仍然无法做到这一点,编写整个事件在一个单一的.js文件与模式,模型和一些代码来创buildlogging然后做这些查询,并张贴。