javascript - Node.js - 使用 Mongoose 创建关系

我有 2 个架构,CustphoneSubdomainCustphone belongs_to 一个 SubdomainSubdomain has_many Custphones .

问题在于使用 Mongoose 创建关系。我的目标是: custphone.subdomain 并获取 Custphone 所属的子域。

我的架构中有这个:

SubdomainSchema = new Schema
    name : String

CustphoneSchema = new Schema
    phone : String
    subdomain  : [SubdomainSchema]

当我打印 Custphone 结果时,我得到:

{ _id: 4e9bc59b01c642bf4a00002d,
  subdomain: [] }

Custphone 结果在 MongoDB 中有 {"$oid": "4e9b532b01c642bf4a000003"} 时。

我想做custphone.subdomain,获取custphone的子域对象。

最佳答案

听起来您想尝试 Mongoose 中的新 populate 功能。

使用上面的示例:

var Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId;

SubdomainSchema = new Schema
    name : String

CustphoneSchema = new Schema
    phone : String
    subdomain  : { type: ObjectId, ref: 'SubdomainSchema' }

subdomain 字段将更新为“_id”,例如:

var newSubdomain = new SubdomainSchema({name: 'Example Domain'})
newSubdomain.save()

var newCustphone = new CustphoneSchema({phone: '123-456-7890', subdomain: newSubdomain._id})
newCustphone.save()

要真正从 subdomain 字段中获取数据,您将不得不使用稍微复杂的查询语法:

CustphoneSchema.findOne({}).populate('subdomain').exec(function(err, custPhone) { 
// Your callback code where you can access subdomain directly through custPhone.subdomain.name 
})

https://stackoverflow.com/questions/7810892/

相关文章:

mongodb - 如何查找然后聚合

node.js - Node.js 和 Mongoose 的管理面板

mongodb - MongoDB 和 CouchDB 是完美的替代品吗?

mongodb - 有没有限制 mongodb 内存使用的选项?

MongoDB - 如何查询集合中的嵌套项?

mongodb - mongodb可以作为嵌入式数据库使用吗?

windows - Mongodb:连接127.0.0.1:27017失败,原因:errno:100

mongodb - MongoDB 将写入锁定到什么级别? (或 : what does it me

java - 使用 MongoDB 进行单元测试

mongodb - 使用 Mongoose 找不到按 ObjectId 搜索的文档