【问题标题】:How do you define a nested object to an existing schema in Mongoose?如何在 Mongoose 中为现有模式定义嵌套对象?
【发布时间】:2011-12-06 08:29:50
【问题描述】:

假设我有两个猫鼬模式:

var AccountSchema = new Schema({ 
       userName: String
     , password: String
})
var AgentSchema = new Schema({
     Name : String
   , Account: AccountSchema
})

是否可以将 AccountSchema 添加到 AgentSchema 而不是一个集合?

【问题讨论】:

  • Account 字段应该是指向实际 Account 对象数据的 ObjectID。

标签: node.js mongoose


【解决方案1】:

看起来不可能。这两种解决方案是使用 DocumentId 或 virtuals:

ObjectId:

var mongoose = require('mongoose')
  , Schema = mongoose.Schema
  , ObjectId = Schema.ObjectId;

var AccountSchema = new Schema({ 
       userName: String
     , password: String
})
var AgentSchema = new Schema({
     name : String
   , account: {type: ObjectId}
})

虚拟:

var AccountSchema = new Schema({ 
       userName: String
     , password: String
})
var AgentSchema = new Schema({
     name : String
   , _accounts: [AccountSchema]
})

AgentSchema.virtual('account') 
   .set(function(account) { this._accounts[0] = account; }) 
   .get(function() { return this._accounts.first(); }); 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-06
    • 1970-01-01
    • 2019-12-21
    • 1970-01-01
    • 2021-05-24
    • 2020-04-22
    • 1970-01-01
    • 2017-07-06
    相关资源
    最近更新 更多