简体   繁体   中英

Mongoose get object in array of objects

I am using mongoose and I am trying to get users from my mongodb database, Here is what part of my json looks like

"hpCDaKverVWEYukAhAcM8NU6SP73" : {
      "admin" : false,
      "booksBorrowed" : [ {
        "id" : "9780321831552",
        "timeStamp" : 1618881802437
      }, {
        "id" : "9780007204496",
        "timeStamp" : 1618881803678
      }, {
        "id" : "9780316491297",
        "timeStamp" : 1618882675513
      }, {
        "id" : "9780440335160",
        "timeStamp" : 1618882676756
      }, {
        "id" : "9781482287325",
        "timeStamp" : 1618887153684
      } ],

I am trying to get the books borrowed array

i tried creating a new schema like this

const BorrowedBook = new Schema({
    id : {type: String, default: ''},
    timeStamp : {type: Number, default: 0},
})

then doing this in mongoose.model

booksBorrowed: [BorrowedBook]

then I do this in server.js

const User = require('./models/user')
app.get('/api/users', function (req, res) {
    User.find(function (err, users) {
        console.log(users)
    })
})

but it just prints this booksBorrowed: [ [Object], [Object], [Object], [Object], [Object] ],

What am I doing wrong?

You are doing nothing wrong, its just console.log(users) printing this, since it doesnt print nested lvl objects.

You can do console.log(JSON.stringify(users)) or console.dir(users) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM