【问题标题】:Why mongoose.model('Model').Schema is going wrong?为什么 mongoose.model('Model').Schema 出错了?
【发布时间】:2012-10-06 02:07:21
【问题描述】:

我找不到我做错了什么... 我正在尝试在 mongoose 模型中定义子文档,但是当我将 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,id 和默认属性已正确设置。但是对于加载的 CommentSchema2,它会出错。

我尝试使用“人口”版本,但这不是我想要的。我不想使用其他集合。

有谁知道怎么回事?谢谢!

猫鼬 v3.3.1

nodejs v0.8.12

完整要点:https://gist.github.com/de43219d01f0266d1adf

【问题讨论】:

    标签: javascript node.js mongoose


    【解决方案1】:

    模型的 Schema 对象可作为 Model.schema 访问,而不是 Model.Schema

    所以将你的要点的第 20 行更改为:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-04
      • 2022-12-22
      • 1970-01-01
      • 1970-01-01
      • 2021-11-03
      • 2020-01-25
      • 1970-01-01
      相关资源
      最近更新 更多