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

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

问题描述

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

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的填充功能来简化您的查询。为此,您可以执行以下操作:

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.

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

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