node.js - Mongoose 居住

标签 node.js mongodb mongoose

这是我的测试代码,我不知道为什么它不起作用,因为它与测试 'populating multiple children of a sub-array at a time' 非常相似.

var mongoose = require('mongoose'),
    Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId;

mongoose.connect('mongodb://localhost/testy');

var UserSchema = new Schema({
    name: String
});

var MovieSchema = new Schema({
    title: String,
    tags: [OwnedTagSchema]
});

var TagSchema = new Schema({
    name: String
});

var OwnedTagSchema = new Schema({
    _name: {type: Schema.ObjectId, ref: 'Tag'},
    _owner: {type: Schema.ObjectId, ref: 'User'}
});

var Tag = mongoose.model('Tag', TagSchema),
    User = mongoose.model('User', UserSchema),
    Movie = mongoose.model('Movie', MovieSchema);
    OwnedTag = mongoose.model('OwnedTag', OwnedTagSchema);

User.create({name: 'Johnny'}, function(err, johnny) {
    Tag.create({name: 'drama'}, function(err, drama) {
        Movie.create({'title': 'Dracula', tags:[{_name: drama._id, _owner: johnny._id}]}, function(movie) {

            // runs fine without 'populate'
            Movie.find({}).populate('tags._owner').run(function(err, movies) {
                console.log(movies);
            });
        });
    })
});

产生的错误是

node.js:201
        throw e; // process.nextTick error, or 'error' event on first tick
              ^
TypeError: Cannot call method 'path' of undefined
    at /Users/tema/nok/node_modules/mongoose/lib/model.js:234:44

更新

摆脱 OwnedTag 并像这样重写 MovieSchema

var MovieSchema = new Schema({
    title: String,
    tags: [new Schema({
        _name: {type: Schema.ObjectId, ref: 'Tag'},
        _owner: {type: Schema.ObjectId, ref: 'User'}
    })]
});

工作代码https://gist.github.com/1541219

最佳答案

您的变量 OwnedTagSchema 必须在使用之前定义,否则您最终会这样做:

var MovieSchema = new Schema({
  title: String,
  tags: [undefined]
});

将它移到 MovieSchema 定义之上。

关于node.js - Mongoose 居住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8682313/

相关文章:

javascript - 如何使用 Visual Studio 2013 和 Node Tools NTVS 调试 node.js 应用程序

node.js - Express 4 应用程序 - Node ./bin/www X nodejs ./bin/www

javascript - nodejs UTF-8编码字符串有黑色问号

node.js - 为 session 设置服务器端 cookie 的正确方法

java - MongoDB 匹配数组中的所有元素

mongodb - 使用多个装饰器将 Type-GraphQL 与 Typegoose 结合起来

javascript - 由于 Mongoose 查询/ promise 而无法获取所需的数据

node.js - 将 mongoose 连接到 mongoDB atlas 和 nodejs

mongodb - Pentaho 中没有 MongoDB 选项

javascript - Mongoose findOneAndUpdate 和 upsert 不返回错误,不影响文档