Почему mongoose.model('Model').Schema работает неправильно?

Я не могу найти, что я делаю неправильно... Я пытаюсь определить поддокументы в моделях мангуста, но когда я разделяю определения схемы на другой файл, детская модель не соблюдается.

Во-первых, определение схемы комментария:

var CommentSchema = new Schema({
    "text": { type: String },
    "created_on": { type: Date, default: Date.now }
});
mongoose.model('Comment', CommentSchema);

Затем создаем другую схему, загружая ее из mongoose.model() (как если бы мы загружали ее из другого файла

var CommentSchema2 = mongoose.model('Comment').Schema;

Теперь определяем родительскую схему:

var PostSchema = new Schema({
    "title": { type: String },
    "content": { type: String },
    "comments": [ CommentSchema ],
    "comments2": [ CommentSchema2 ]
});
var Post = mongoose.model('Post', PostSchema);

И немного тестов

var post = new Post({
    title: "Hey !",
    content: "nothing else matter"
});

console.log(post.comments);  // []
console.log(post.comments2); // [ ]  // <-- space difference

post.comments.unshift({ text: 'JOHN' }); 
post.comments2.unshift({ text: 'MICHAEL' }); 

console.log(post.comments);  // [{ text: 'JOHN', _id: 507cc0511ef63d7f0c000003,  created_on: Tue Oct 16 2012 04:07:13 GMT+0200 (CEST) }]
console.log(post.comments2); // [ [object Object] ] 

post.save(function(err, post){

    post.comments.unshift({ text: 'DOE' });
    post.comments2.unshift({ text: 'JONES' });

    console.log(post.comments[0]); // { text: 'DOE', _id: 507cbecd71637fb30a000003,  created_on: Tue Oct 16 2012 04:07:13 GMT+0200 (CEST) } // :-)
    console.log(post.comments2[0]); // { text: 'JONES' }  // :'-(

    post.save(function (err, p) {
        if (err) return handleError(err)

        console.log(p);
    /*
    { __v: 1,
      title: 'Hey !',
      content: 'nothing else matter',
      _id: 507cc151326266ea0d000002,
      comments2: [ { text: 'JONES' }, { text: 'MICHAEL' } ],
      comments:
       [ { text: 'DOE',
           _id: 507cc151326266ea0d000004,
           created_on: Tue Oct 16 2012 04:07:13 GMT+0200 (CEST) },
         { text: 'JOHN',
           _id: 507cc151326266ea0d000003,
           created_on: Tue Oct 16 2012 04:07:13 GMT+0200 (CEST) } ] }
    */

        p.remove();
    });    
});

Как видите, в CommentSchema идентификаторы и свойства по умолчанию установлены правильно. Но с загруженной CommentSchema2 все идет не так.

Я пытался использовать «популяционную» версию, но это не то, что мне нужно. Я не хочу использовать другую коллекцию.

Кто-нибудь из вас знает, что не так? Спасибо !

мангуст v3.3.1

узлы v0.8.12

Полный список: https://gist.github.com/de43219d01f0266d1adf


person Balbuzar    schedule 16.10.2012    source источник


Ответы (1)


Объект схемы модели доступен как Model.schema, а не Model.Schema.

Итак, измените строку 20 своего содержания на:

var CommentSchema2 = mongoose.model('Comment').schema;
person JohnnyHK    schedule 16.10.2012