mongodb - Mongoose 模式引用和填充

标签 mongodb mongoose mean-stack

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

我当前的架构如下所示,

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)})

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

最佳答案

This link显示做引用的方式例如如下:

粉丝:[{ type: Number, ref: 'Person' }]

您是否尝试过以下方法?

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

此外,您的模型名称是“calendarlist”。您的收藏称为“日历列表”吗?因为“Mongoose 会根据 this link 自动查找您的型号名称的复数形式” .

关于mongodb - Mongoose 模式引用和填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43462099/

相关文章:

node.js - 当我们在nodejs中使用mongoose从mongodb中选择复杂对象时,有什么方法可以重命名路径吗?

node.js - 无法连接到数据库MongoParseError : Unescaped at-sign in authority section

javascript - Express 路由器无法处理发布请求

node.js - 在 Mongoose 中填充 + 聚合

javascript - 使用 Mongoose 更新 Node.js 中 find() 方法返回的结果

mongodb - 为什么 mongo 没有通过命令行连接到我的表?

node.js 检查 mongoose 中的重复值

javascript - Mongoose 的保存回调是如何工作的?

mongodb - 如何使用 MongoDB 和 C# 驱动程序查询子文档集合

linux - 无法在linux上安装mongodb