MongoDB,Mongoose:如何在找到的文档中找到子文档?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21142524/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MongoDB, Mongoose: How to find subdocument in found document?
提问by gial
I'm stuck on trying to get subdocument by _id
in found document.
我一直试图_id
在找到的文档中获取子文档。
Example Schema
示例架构
var User = mongoose.Schema({
name: String,
photos: [{src: String, title: String}]
});
var Team = db.model('Team', Team);
Now I'm getting one user:
现在我有一个用户:
myUser = User.findOne(...)...
How can I get now src
of his photo by it's _id
(or title
)?
我现在如何src
通过它_id
(或title
)获得他的照片?
Something like:
就像是:
myUser.photos.findOne({'_id': myId})
回答by srquinn
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.
您需要为嵌入的文档创建一个 NEW Schema,或者将类型声明保留为空白数组,以便mongoose
解释为Mixed
类型。
var userSchema = new mongoose.Schema({
name: String,
photos: []
});
var User = mongoose.model('User', userSchema);
-- OR --
- 或者 -
var userSchema = new mongoose.Schema({
name: String,
photos: [photoSchema]
});
var photoSchema = new mongoose.Schema({
src: String,
title: String
});
var User = mongoose.model('User', userSchema);
And then you can save thusly:
然后你可以这样保存:
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' }
});
-- OR --
- 或者 -
You can use the special id()
method in embedded docs to look up by id:
您可以使用id()
嵌入式文档中的特殊方法按 id 查找:
User.findOne({name: 'Bob'}, function (err, user) {
user.photos.id(photo._id);
});
You can read more here: http://mongoosejs.com/docs/subdocs.html
您可以在此处阅读更多信息:http: //mongoosejs.com/docs/subdocs.html
Make sure you DON'Tregister 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)
确保不要使用 mongoose 注册架构,否则它将创建一个新集合。还要记住,如果经常搜索子文档,最好使用如下所示的引用和人口。即使它两次访问数据库,由于索引,它的速度要快得多。此外,mongoose
还会关注双重嵌套文档(即孩子们也有儿童文档)
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);
});
Relevant docs can be found here http://mongoosejs.com/docs/populate.html
相关文档可以在这里找到http://mongoosejs.com/docs/populate.html
回答by Dominic
Adding to srquinn's answer, from my limited experience I thought populate
was for joining documents from different collections together?
添加到 srquinn 的答案,根据我有限的经验,我认为populate
是将来自不同集合的文档连接在一起?
I think here you could just do User.findOne({ name: 'foo' }, 'photos')
which is shorthand for:
我认为在这里你可以做以下User.findOne({ name: 'foo' }, 'photos')
简写:
const query = User.findOne({ name: 'foo' })
query.select('photos')