如何查询数组中的Id?猫鼬

时间:2015-11-12 06:19:43

标签: node.js mongodb mongoose

如何使用mongoose

查询数组中的特定_id

这是代码

public MainPage()
{
    this.InitializeComponent();

    var items = new Item[]
    {
        new Item { Name="1"},
        new Item { Name="2"},
        new Item { Name="3"},
        new Item { Name="4"},
        new Item { Name="5"},
        new Item { Name="6"},
        new Item { Name="7"},
        new Item { Name="8"},
        new Item { Name="9"},
        new Item { Name="10"},
    };

    var collection = new ObservableCollection<Item>();

    this.FlipView.ItemsSource = collection;

    foreach (var item in items)
    {
        collection.Add(item);
    }

    Synergist.FlipViewExtensions.SetIsLooping(this.FlipView, true);
}

如何专门查询教育ID?

我的尝试

var userSchema = new mongoose.Schema({
   resume: {
      educations: [{
          school: String,
          year: String
      }]
   }
});

已存储的数据

enter image description here

User.findById({ 'resume.educations._id': req.body.education_id}, function(err, foundUser){ console.log(foundUser) --> Keep returning Undefined }); - &gt; console.log(req.body.education_id)

1 个答案:

答案 0 :(得分:1)

您可以将$elementMatch与findOne一起使用

User.findOne({'resume.educations': {$elemMatch: {_id: '564497eb366f59b004e9d17e'}}}, function(err, foundUser){

   console.log(foundUser);
   // output
   // [ { resume: { educations: [ [Object] ] },
   //   __v: 0,
   //   _id: 564497eb366f59b004e9d17d } ]

});

这是我试过的文件并且有效

{
        "_id" : ObjectId("564497eb366f59b004e9d17d"),
        "resume" : {
                "educations" : [
                        {
                                "school" : "school name",
                                "year" : "1999",
                                "_id" : ObjectId("564497eb366f59b004e9d17e")
                        }
                ]
        },
        "__v" : 0
}