【问题标题】:Mongoose populate returning nullMongoose 填充返回 null
【发布时间】:2014-11-02 01:06:31
【问题描述】:

我的代码包含 2 个模型,内容和电影。电影有对内容的引用。 在我尝试填充内容时的“电影”查询中,返回 null。

  1. 内容模型

    '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);
    
  2. 电影模型

    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);
    

这是我在服务器端的控制器:

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"
    }
]

如果我从查询中删除填充,即使我可以在输出中看到 contentId,为什么输出为空。

【问题讨论】:

    标签: node.js mongodb mongoose mean mean-stack


    【解决方案1】:

    没关系,找到问题了。

    代码没有问题。我在“内容”表而不是“内容”表中输入了数据。叹息。

    【讨论】:

      猜你喜欢
      • 2019-06-17
      • 1970-01-01
      • 2014-11-20
      • 2020-11-11
      • 1970-01-01
      • 2014-12-12
      • 2020-11-24
      • 1970-01-01
      • 2016-12-04
      相关资源
      最近更新 更多