【发布时间】:2020-07-03 10:50:52
【问题描述】:
我正在使用 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 子文档数组有几个元素:
但是,如上面的 console.log 输出所示,rounds 将作为空数组返回。我已经确认(a)rounds 实际上是一个数组(使用Array.isArray())并且(b)rounds 没有元素(thisUser.rounds.length === 0)。
难道我不能通过thisUser.rounds 访问所有子文档吗?我做错了什么?
【问题讨论】:
-
您使用的是什么版本的 Mongo?以下有帮助吗? github.com/Automattic/mongoose/issues/6141 能否也显示
roundSchema以及注册模型的指令顺序? -
我已更新问题以包括版本号 (6.4.1)、
roundSchema和说明顺序。我在您提到的帖子中看不到太多相关性。感谢您的帮助!