无法查询子子文档

Cannot Query sub sub documents

我无法访问子文档我想查询子文档实现后端分页以便我可以在单独的页面中呈现它们

我尝试使用点符号 something.something.something,甚至使用这个 ["something"]["something"]["something"] 数组,因为我最近发现对象是数组种类

这是模型架构 ||子架构

const modelSchema = new mongoose.Schema({
  modelname: {
    type: String,
    required: true,
    minlength: 5,
    maxlength: 250
  }
});

这是自行车架构 ||父架构

const bikeSchema = new mongoose.Schema({
 make: {
    type: makeSchema,
    required: true
  }
})

数据在Mongodb

中的存储方式
 "_id" : ObjectId("5d5e13e8edcbbf038c1f9b8e"),
"make" : {
        "_id" : ObjectId("5d40f0b40268d80ac8c30973"),
        "makename" : "{ _id: 5d40f0b40268d80ac8c30973, makename: 'ducatii', __v: 0 }"
}

为了查询 makename ducatii,根据文档的预期输出是做这样的事情

console.log(自行车[0]["make"]["makename"]["makename"])

或者这个 console.log(自行车[0].make.makename.makename)

注意两点:

  1. 如果返回的结果是一个MongoDB游标对象,则不能通过数组索引访问。您需要使用适当的方法从光标中检索项目。
  2. 您的第一个 makename 字段指向 JSON 字符串,而不是对象。您不能从 JSON 字符串访问嵌套的 makename.makename。在访问嵌套的 属性.
  3. 之前,您必须首先将 JSON 解码为一个对象

这似乎与您存储子文档的方式有关。

例如:

bikes[0].make.makename 实际上是一个字符串,不是一个有效的对象。您也不能 JSON.parse 这个字符串,因为您必须用转义双引号将每个 key/value 括起来。

如果您能够正确存储此子文档,那么您应该可以按照您期望的方式使用该对象!

要将文档嵌入到文档中,您必须像下面那样执行此操作

var childSchema = new Schema({ name: 'string' });

var parentSchema = new Schema({
  // Array of subdocuments
  children: [childSchema],
  // Single nested subdocuments. Caveat: single nested subdocs only work
  // in mongoose >= 4.2.0
  child: childSchema
});

你的情况

const modelSchema = new mongoose.Schema({
  makename: {
    type: String,
    required: true,
    minlength: 5,
    maxlength: 250
  }
});

const bikeSchema = new mongoose.Schema({
 make: {
    makename: modelSchema
  }
})

然后你可以像

一样访问它
console.log(bikes[0]["make"]["makename"]["makename"])