请问如何使用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有什么操作能直接获得这样的吗,感激不尽~


慕的地6264312
浏览 1148回答 2
2回答

FishWithSmile

Schema里memo数组里不存对象,直接放String不就可以吗?

蝴蝶刀刀

两种做法: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)     } );返回结果:2、mongo里可以只返回匹配的数组中的记录。具体做法参考:mongo官网注:以上是本机运行的结果。使用的mongoose版本为:5.2.5mongo版本为:3.4
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript