[英]How do you define a nested object to an existing schema in Mongoose?
Say I have two mongoose schemas: 假设我有两个猫鼬模式:
var AccountSchema = new Schema({
userName: String
, password: String
})
var AgentSchema = new Schema({
Name : String
, Account: AccountSchema
})
is there anyway to add AccountSchema to the AgentSchema without it being a collection? 无论如何将AccountSchema添加到AgentSchema而不是它是一个集合?
It doesn't look like it's possible. 它看起来不太可能。 The two solutions are to either use a DocumentId or virtuals: 这两个解决方案要么使用DocumentId,要么使用虚拟:
ObjectId: 的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}
})
Virtuals: 虚函数:
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(); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.