MongoDB、Mongoose:如何在找到的文档中查找子文档? [英] MongoDB, Mongoose: How to find subdocument in found document?

查看:48
本文介绍了MongoDB、Mongoose:如何在找到的文档中查找子文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直试图在找到的文档中通过 _id 获取子文档.

I'm stuck on trying to get subdocument by _id in found document.

示例架构

var User = mongoose.Schema({
        name:       String,
        photos:    [{src: String, title: String}]
    });
var Team = db.model('Team', Team);

现在我有一个用户:

myUser = User.findOne(...)...

我现在如何通过_id(或title)获得他照片的src?

How can I get now src of his photo by it's _id (or title)?

类似于:

myUser.photos.findOne({'_id': myId})

推荐答案

您需要为嵌入的文档创建一个 NEW Schema,或者将类型声明保留为空数组,以便 mongoose 解释为Mixed 类型.

You need to either create a NEW Schema for your embedded documents, or leave the type declaration as a blank array so mongoose interprets as a Mixed type.

var userSchema = new mongoose.Schema({
  name: String,
  photos: []
});
var User = mongoose.model('User', userSchema);

-- 或 --

var userSchema = new mongoose.Schema({
  name: String,
  photos: [photoSchema]
});

var photoSchema = new mongoose.Schema({
  src: String,
  title: String
});

var User = mongoose.model('User', userSchema);

然后你可以这样保存:

var user = new User({
  name: 'Bob',
  photos: [ { src: '/path/to/photo.png' }, { src: '/path/to/other/photo.png' } ]
});

user.save();

从这里,您可以简单地使用数组原语来查找您嵌入的文档:

From here, you can simply use array primitives to find your embedded docs:

User.findOne({name: 'Bob'}, function (err, user) {

  var photo = user.photos.filter(function (photo) {
    return photo.title === 'My awesome photo';
  }).pop();

  console.log(photo); //logs { src: '/path/to/photo.png', title: 'My awesome photo' }
});

-- 或 --

您可以在嵌入式文档中使用特殊的 id() 方法按 id 查找:

-- OR --

You can use the special id() method in embedded docs to look up by id:

User.findOne({name: 'Bob'}, function (err, user) {
    user.photos.id(photo._id);
});

您可以在这里阅读更多信息:http://mongoosejs.com/docs/subdocs.html

You can read more here: http://mongoosejs.com/docs/subdocs.html

确保您不要向 mongoose 注册架构,否则它将创建一个新集合.还要记住,如果经常搜索子文档,最好使用如下所示的引用和人口.即使它两次访问数据库,由于索引,它的速度要快得多.此外,mongoose 会关注双重嵌套文档(即孩子们也有孩子们的文档)

Make sure you DON'T register the schema with mongoose, otherwise it will create a new collection. Also keep in mind that if the child documents are searched for often, it would be a good idea to use refs and population like below. Even though it hits the DB twice, its much faster because of indexing. Also, mongoose will bonk on double nesting docs (i.e. The children have children docs as well)

var user = mongoose.Schema({
  name: String,
  photos: [{ type: Schema.Types.ObjectId, ref: 'Photo' }]
});

var photo = mongoose.Schema({
  src: String,
  title: String
});

User
  .findOne({ name: 'foo' })
  .populate('photos')
  .exec(function (err, user) {
    console.log(user.photos[0].src);
  });

相关文档可以在这里找到http://mongoosejs.com/docs/populate.html

Relevant docs can be found here http://mongoosejs.com/docs/populate.html

这篇关于MongoDB、Mongoose:如何在找到的文档中查找子文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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