请问如何使用mongoose查询内嵌数据呢

const userSchema = new Schema({
  name:{type:String},
  clubnumber:{type:String},
  memo:[{
    memos:{type:String}
  }]
})

数据结构如上,现在是想匹配name和clubnumber,来查询库下的所有memo

db.userModel.findOne({name:name,clubnumber:clubnumber},(e,d)=>{
            console.log(d.memo);
        })

小弟这样写的话,控制台出来的数据是

[
    { memos:xxx,id:xxxx},
    { memos:xxx1,id:xxxxx}
]

小弟想得到的数据结构是


    {memos1,memos2,memos3}//所有memos的一个数组

小弟现在能想到用遍历重新创建一个数组,但是有大神知道mongoose有什么操作能直接获得这样的吗,感激不尽~

阅读 2.5k
1 个回答

两种做法:

1、在创建数组模型的时候去掉_id的选项。
//定义
const userChildSchema = new Schema(
    { memos: { type: String } },
    { _id: false } //子对象里去掉_id
);

const userSchema = new Schema({
    name: { type: String },
    clubnumber: { type: String },
    memo: [userChildSchema]
});

//查询
userModel.findOne({ name: "nameeeeee" },
    { "memo": 1 },  //select
    null,
    function (err, cursor) {
        console.log(cursor.toJSON().memo)
    }
);

返回结果:

clipboard.png

2、mongo里可以只返回匹配的数组中的记录。

具体做法参考:mongo官网

注:
  • 以上是本机运行的结果。
  • 使用的mongoose版本为:5.2.5
  • mongo版本为:3.4
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题