【问题标题】:Unable to query sub document mongoose无法查询子文档猫鼬
【发布时间】:2017-06-01 22:13:21
【问题描述】:

我有这样的模式和我,试图使用_id从数组中获取文档。这是我正在工作的第一个 Mongo 项目,请帮助我如何实现。我基本上是想检索id对应的子文档并更新其中的一些数据。

    var PhoneSchema = new mongoose.Schema({
            type: String,
            number: String
        });

        var StudentSchema =  new mongoose.Schema({
            name: String,
            dept: String,
            phone: [PhoneSchema]    
        });

var Phone = mongoose.model('Phone',PhoneSchema);
var Student = mongoose.model('Student',StudentSchema);

我尝试了以下方法,但都没有奏效。

方法 1:当我在控制台中尝试相同的方法时,它会为我提供父文档以及对应于 phoneId 的子文档

Student.findOne({"phone._id":new mongoose.Schema.Types.ObjectId(phoneId) }, {'phone.$':1}, function(err,     student)       { 

}

方法2:根据猫鼬文档检索子文档,在这种情况下,我收到异常说电话未定义

Student.phone.Id(phoneId); 

我已通过从以下查询中删除架构来解决此问题

Student.findOne({"phone._id":new mongoose.Types.ObjectId(phoneId) }, {'phone.$':1}, function(err,     student)       { 

}

【问题讨论】:

  • 你想达到什么目的? StudentSchema 文档或 PhoneSchema 文档?
  • 我想获取电话架构文档并更新电话号码。

标签: mongodb mongoose


【解决方案1】:

我试图解决您的要求。以下代码完成了这项工作。

var PhoneSchema = new mongoose.Schema({
            type: String,
            number: String
        });

var StudentSchema =  new mongoose.Schema({
            name: String,
            dept: String,
            phone: [PhoneSchema]    
        });

var Phone = mongoose.model('Phone',PhoneSchema);
var Student = mongoose.model('Student',StudentSchema);

var newPhone = new Phone({
    type: 'ios', number: '9030204942'
});

var newStudent = new Student({
    name:'Pankaj',
    dept:'cse',
    phone:newPhone
});

// newStudent.save(function(err, ph) {
//     if (err) return console.error(err);

// });

Student.findOne({"phone._id":mongoose.Types.ObjectId('587e6409e06170ba1708dc21') },{_id:0,phone:1}, function(err,     phone)       { 
        if(err){
            console.log(err)
        }
        console.log(phone);
});

找到以下带有结果的屏幕截图

【讨论】:

  • 当我在 mongo shell 中尝试这个时,我确实得到了结果,但是当我使用 mongoose 尝试同样的结果时,它没有返回任何文档。这是我在上面的问题中发布的方法 1。感谢您的回复。
  • 之前你在查询中有这个: {"phone._id":new mongoose.Schema.Types.ObjectId(phoneId) }, {'phone.$':1} 一旦你把它改成: {"phone._id":mongoose.Types.ObjectId('587e6409e06170ba1708dc21') },{_id:0,'phone':1} 它工作正常吗?该解决方案适用于猫鼬。我已经发送了相同的屏幕截图。
  • 我的解决方案有两件事:删除关键字 Schema 并在投影中添加 _id:0。我想你没有注意到并认为它与你的方法 #1 相同
  • 是的,你是对的 Pankaj 我忽略了它,事实上我不知道它们的行为不同。我会将您的答案标记为已接受。
猜你喜欢
  • 2015-06-26
  • 2019-10-19
  • 2014-03-21
  • 1970-01-01
  • 2013-10-21
  • 2013-04-16
  • 1970-01-01
  • 2021-08-29
  • 1970-01-01
相关资源
最近更新 更多