MongoDB findOne()返回空的子文档数组

时间:2020-03-22 22:29:34

标签: mongodb express mongoose

我正在使用Mongoose和MongoDB v.6.4.1。我已经使用以下Mongoose模式定义了带有嵌入式子文档的文档集合:

import mongoose, { Collection } from 'mongoose';
const connectStr = 'mongodb://localhost/appdb';
mongoose.set('useFindAndModify', false);

//Open connection to database
mongoose.connect(connectStr, {useNewUrlParser: true, useUnifiedTopology: true})
  .then(
    () =>  {console.log(`Connected to ${connectStr}.`)},
    err => {console.error(`Error connecting to ${connectStr}: ${err}`)}
  );

//Define schema that maps to a document in the Users collection in the appdb
//database.
const Schema = mongoose.Schema;

const roundSchema = new Schema({
  date: {type: Date, required: true},
  course: {type: String, required: true},
  type: {type: String, required: true, enum: ['practice','tournament']},
  holes: {type: Number, required: true, min: 1, max: 18},
  strokes: {type: Number, required: true, min: 1, max: 300},
  minutes: {type: Number, required: true, min: 1, max: 240},
  seconds: {type: Number, required: true, min: 0, max: 60},
  SGS: {type: Number, 
        default: function(){return (this.strokes * 60) + (this.minutes * 60) + this.seconds}
       },
  notes: {type: String, required: true}
});

const userSchema = new Schema({
  id: {type: String, required: true}, //unique identifier for user
  password: String, //unencrypted password (for now!)
  displayName: {type: String, required: true}, //Name to be displayed within app
  authStrategy: {type: String, required: true}, //strategy used to authenticate, e.g., github, local
  profileImageUrl: {type: String, required: true}, //link to profile image
  rounds: [roundSchema],
  securityQuestion: {type: String},
  securityAnswer: {type: String, required: function() {return this.securityQuestion ? true: false}}
});

//Convert schema to model
const User = mongoose.model("User",userSchema); 

在Express.js GET路由中,我使用以下代码查询特定文档:

try {
    let thisUser = await User.findOne({id: req.params.userId});
    console.log("thisUser: " + JSON.stringify(thisUser));
    if (!thisUser) {
      return res.status(400).send("No user account with specified userId was found in database.");
    } else {
      return res.status(200).json(thisUser.rounds);
    }
  } catch (err) {
    console.log(err);
    return res.status(400).message("Unexpected error occurred when looking up user in database: " + err);
  }

我的console.log语句确认上述路由实际上已获得所需的文档,例如:

thisUser: {"_id":"5e6704234f3864318caedd12","id":"chundhau@gmail.com","password":"GoCougs20","displayName":"chundhau@gmail.com","authStrategy":"local","profileImageUrl":"https://www.gravatar.com/avatar/4b565c54d37b3f5ad4caa1c129e865b8","securityQuestion":"First pet?","securityAnswer":"Daisy","__v":0,"rounds":[]}

当我在MongoDB Compass社区中查看同一文档时,我可以确认其rounds子文档数组包含多个元素:

MongoDB Compass Community Screeenshot

但是,如上面的console.log输出所示, rounds将以空数组的形式返回。我已经确认(a)rounds实际上是一个数组(使用Array.isArray()),并且(b)rounds没有元素(thisUser.rounds.length === 0)。

我不能通过thisUser.rounds访问所有子文档吗?我做错了什么?

1 个答案:

答案 0 :(得分:1)

我找到了解决方案。我改变了:

let thisUser = await User.findOne({id: req.params.userId});

let thisUser = await User.findOne({id: req.params.userId}).lean();

奇迹般地,thisuser.rounds不再是空的。相反,它包含我在MongoDB Compass社区中检查文档时可以看到的所有数组元素!

虽然此解决方案有效,但我不知道为什么为什么有效。如果有人可以帮助我了解这里发生的事情,我将不胜感激!