node.js - 如何在 Mongoose 中为现有模式定义嵌套对象?

标签 node.js mongoose

假设我有两个 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/

相关文章:

javascript - javascript回调和匿名函数的范围是什么?

javascript - Passport LocalStrategy 注册重定向问题

node.js - 通过 Node.js 连接到远程 Docker

node.js - TypeScript - 如何结合使用 Mongoose 填充来定义模型?

javascript - findByIdAndUpdate 不断被捕获在 .catch 中

javascript - mongoose/mongodb 计算统计数据的最佳方法

javascript - 从 mongodb 回调将值设置为外部变量

javascript - React setState 在变量初始化之前保持运行

javascript - express-session 不会设置 cookie connect.sid

java - 在 Java 中执行 Linux nodejs 命令行