【问题标题】:Mongoose Schema Ref & Populate猫鼬模式参考和填充
【发布时间】:2017-09-13 16:45:13
【问题描述】:

我想用来自同一集合的一组文档填充我的数据库查询。在我无法判断错误是在我的模型中还是在我的查询中之前从未引用过。

我当前的架构是这样的,

var mongoose = require('mongoose'),
    Schema = mongoose.Schema,
    shortid = require('shortid')

/* Calendar Schema */
var CalendarSchema = mongoose.Schema({
  _id: {
    type: String,
    unique: true,
    'default': shortid.generate
  }, 
  title:String,
  mixin: [{_id: { type: String, ref: 'calendarlist' }}],
  notes: Array
})

module.exports = mongoose.model('calendarlist', CalendarSchema)

我的示例文档如下所示,

{
    "_id" : "mixtest",
    "mixin" : [ 
        {
            "$ref" : "calendarlist",
            "$id" : "cVkKRkNtB-"
        }
    ],
    "title" : "mix test",
    "__v" : 3,
    "notes" : []
}

and


{
    "_id" : "cVkKRkNtB-",
    "title" : "found doc",
    "__v" : 3,
    "notes" : []
}

我的查询看起来像这样,

calendarlist.find({}).populate('mixin').sort({
              title: 1
            }).exec(function(err, s) {
              if (err) {console.log(err) }
              console.log(s)})

非常感谢您的建议、提示或一般说明。谢谢。

【问题讨论】:

    标签: mongodb mongoose mean-stack


    【解决方案1】:

    This link 表示引用方式如下:

    fans: [{ type: Number, ref: 'Person' }]

    您是否尝试过以下方法?:

    mixin: [ { type: String, ref: 'calendarlist' }],
    

    另外,您的模型名称是“日历列表”。你的收藏被称为“日历列表”吗?因为根据this link,“Mongoose 会自动查找您的型号名称的复数版本”。

    【讨论】:

    • 去掉多余的_id
    • 同样的错误 - { CastError: Cast to string failed for value "DBRef { _bsontype: 'DBRef', namespace: 'calendarlist', oid: 'cVkKRkNtB-', db: undefined }" at path " _id"......
    • 抱歉 - 是的...试过了 - mixin: [ { type: String, ref: 'calendarlist' }],
    • 你的收藏不应该叫日历和你的模型日历吗?
    • 最后,我没有在实际文档中正确引用-“mixin”:[“id1”、“id2”、“id3”等]。 @Treefish-Zhang 非常感谢您的帮助和支持。
    猜你喜欢
    • 2015-01-13
    • 2013-01-25
    • 1970-01-01
    • 1970-01-01
    • 2015-03-16
    • 2014-11-01
    • 2020-08-27
    • 2021-09-19
    • 2020-11-30
    相关资源
    最近更新 更多