MongoDB,Mongoose:如何在找到的文档中找到子文档? [英] MongoDB, Mongoose: How to find subdocument in found document?
问题描述
我一直试图通过找到的文档中的_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
会在双重嵌套文档上退格(即,子级也有子级文档)
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屋!