模式中的猫鼬模式 [英] Mongoose schema within schema

查看:24
本文介绍了模式中的猫鼬模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将架构添加到另一个架构?这似乎无效:

How can I add a schema to another schema? This doesn't seem to be valid:

var UserSchema = new Schema({
    name        : String,
    app_key     : String,
    app_secret  : String
})



var TaskSchema = new Schema({
    name            : String,
    lastPerformed   : Date,
    folder          : String,
    user            : UserSchema
})

我查看了网站,它显示了如何为数组声明它而不是为单个声明.

I checked the website and it shows how to declare it for an array but not for single.

谢谢

推荐答案

有几种方法可以做到这一点.最简单的就是这样:

There are a few ways to do this. The simplest is just this:

var TaskSchema = new Schema({
    name            : String,
    lastPerformed   : Date,
    folder          : String,
    user            : Schema.ObjectId
});

然后,您只需要确保您的应用写入该 ID 并在查询中使用它来根据需要获取相关"数据.

Then you just have to make sure your app is writing that id and using it in queries to fetch "related" data as necessary.

这在按用户id搜索任务时没问题,但在按任务id查询用户时比较麻烦:

This is fine when searching tasks by user id, but more cumbersome when querying the user by task id:

// Get tasks with user id
Task.find({user: user_id}, function(err, tasks) {...});

// Get user from task id
Task.findById(id, function(err, task) {
  User.findById(task.user, function(err, user) {
    // do stuff with user
  }
}

另一种方法是利用 Mongoose 的 populate 功能来简化您的查询.为此,您可以执行以下操作:

Another way is to take advantage of Mongoose's populate feature to simplify your queries. To get this, you could do the following:

var UserSchema = new Schema({
    name        : String,
    app_key     : String,
    app_secret  : String,
    tasks       : [{type: Schema.ObjectId, ref: 'Task'}] // assuming you name your model Task
});

var TaskSchema = new Schema({
    name            : String,
    lastPerformed   : Date,
    folder          : String,
    user            : {type: Schema.ObjectId, ref: 'User'} // assuming you name your model User
});

这样,您对所有用户的查询,包括他们的任务数组可能是:

With this, your query for all users, including arrays of their tasks might be:

User.find({}).populate('tasks').run(function(err, users) {
  // do something
});

当然,这意味着维护两个地方的 id.如果这让您感到困扰,最好坚持使用第一种方法并习惯于编写更复杂(但仍然足够简单)的查询.

Of course, this means maintaining the ids in both places. If that bothers you, it may be best to stick to the first method and just get used to writing more complex (but still simple enough) queries.

这篇关于模式中的猫鼬模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆