Mongoose控制台打印用户实例时部分字段缺失问题求助
Hey there! Let's break down why your console.log(user) is missing fields that clearly exist in your MongoDB database:
1. You're logging a memory-only instance, not the full database document
When you run var user = new User({userid:userid}), you're just creating an in-memory Mongoose Document instance with only the fields you passed (userid) plus Mongoose-generated defaults (_id, empty questions array). This instance hasn't pulled any data from your database yet—so it doesn't know about id, password, or __v that exist in MongoDB.
To get the full document, you need to query the database instead:
// Use findOne to fetch the complete user from MongoDB User.findOne({ userid: userid }) .then(fullUser => { console.log(fullUser); // This will show all fields from the database }) .catch(err => console.error(err));
2. Mongoose Schema configuration might be hiding fields
Double-check your User Schema definition. If fields like password have select: false set, Mongoose will exclude them from default queries:
// Example of a Schema that hides password by default const userSchema = new mongoose.Schema({ userid: String, id: { type: Number, default: 0 }, password: { type: String, select: false }, // This hides the field questions: { type: Array, default: [] } });
If you need to include hidden fields in a query, explicitly request them:
User.findOne({ userid: userid }).select('+password') .then(user => console.log(user));
3. Use toObject() to see all fields in the instance
Mongoose Documents have a wrapper that hides some internal data. To convert it to a plain JavaScript object with all fields, use toObject():
// If you have a saved/fetched user instance console.log(user.toObject());
Bonus: When saving a new user, wait for the save to complete
If you're creating and saving a user, make sure to log the saved instance (which includes all database-generated fields):
async function createUser(userid) { const user = new User({ userid: userid }); const savedUser = await user.save(); console.log(savedUser.toObject()); // Shows all fields from the saved document }
内容的提问来源于stack exchange,提问作者Mani Kant Tiwari

