node.js - Mongoose 填充返回 null

标签 node.js mongodb mongoose mean mean-stack

我的代码包含 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);
    

这是我在服务器端的 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/

相关文章:

mongodb - 有没有办法在 mongoDB 中索引一个文档来填充它的引用?

javascript - 如何将 mongo 查找查询的结果添加到另一个查找查询中

javascript - 如何在 electron shell 中做 oauth 2.0

node.js - 在本地需要 Node 模块

mongodb - 如何处理 PyMongo/MongoEngine AutoReconnect?

Java Mongo索引查询

mongodb 和 pymongo 16Mb 文档大小限制

javascript - Mongoose 使用 $regex 搜索所有字段

node.js - MongoDB: “Could not connect to any servers in your MongoDB Atlas cluster (whitelist)”

mysql 查询返回两个单独的数组