假设我有两个 Mongoose 模式:
var AccountSchema = new Schema({
userName: String
, password: String
})
var AgentSchema = new Schema({
Name : String
, Account: AccountSchema
})
是否可以将 AccountSchema 添加到 AgentSchema 而不是集合?
最佳答案
这看起来不太可能。两种解决方案是使用 DocumentId 或 virtuals:
对象编号:
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(); });
关于node.js - 如何在 Mongoose 中为现有模式定义嵌套对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7744271/