我的代码包含 2 个模型,内容和电影。电影引用了内容。 在“电影”查询中,当我尝试填充“内容”时,返回 null。
内容模型
'use strict'; var mongoose = require('mongoose'), validators = require('./validators'), Schema = mongoose.Schema; var contentType = ['M']; var ContentSchema = new Schema({ createdOn: { type: Date, default: Date.now }, name: { type: String, required: true, unique: true, trim: true }, type: { type: String, required: true, enum: contentType, trim: true }, releaseDate: { type: Date }, genres: [{ type: Schema.Types.ObjectId, ref: 'Genre' }], language: { type: Schema.Types.ObjectId, ref: 'Language' }, imagePath: { type: String }, filePath: { type: String } }); mongoose.model('Content', ContentSchema);
电影模特
var mongoose = require('mongoose'), validators = require('./validators'), Schema = mongoose.Schema; var MovieSchema = new Schema({ createdOn: { type: Date, default: Date.now }, contentId: { type: Schema.Types.ObjectId, ref: 'Content' }, cast: { type: [String] }, synopsis: { type: String }, length: { type: Number }, director: { type: String } }); mongoose.model('Movie', MovieSchema);
这是我在服务器端的 Controller :
Movie.find().populate('contentId').exec(function (err, movies) {
if (err) {
return res.json(500, {
error: 'cannot list movies'
});
}
res.json(movies);
});
输出:
[
{
"_id": "540dcdda98fcaefbaf26fd72",
"contentId": null,
"synopsis": "Nice Movie",
"length": 140,
"director": "Foo Bar",
"cast": [],
"createdOn": "2014-09-08T16:38:19.275Z"
}
]
如果我从查询中删除 populate,即使我可以在输出中看到 contentId,为什么输出仍为 null。
最佳答案
没关系,解决问题了。
代码没有问题。我的数据条目位于“内容”表中,而不是“内容”表中。叹息。
关于node.js - Mongoose 填充返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25730585/