1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost:27017/myapp');
const userSchema = new mongoose.Schema({ name: { type: String, required: true, trim: true }, email: { type: String, unique: true, lowercase: true }, age: { type: Number, min: 0, max: 150, default: 0 }, role: { type: String, enum: ['user', 'admin'], default: 'user' }, tags: [String], address: { city: String, street: String, }, }, { timestamps: true, });
userSchema.virtual('isAdult').get(function() { return this.age >= 18; });
userSchema.methods.toJSON = function() { const obj = this.toObject(); delete obj.__v; return obj; };
userSchema.statics.findByEmail = function(email) { return this.findOne({ email }); };
const User = mongoose.model('User', userSchema);
const user = await User.create({ name: 'Alice', email: 'alice@example.com', age: 25 }); const users = await User.find({ age: { $gt: 20 } }).sort({ age: -1 }).limit(10); const updated = await User.findByIdAndUpdate(user._id, { age: 26 }, { new: true }); await User.findByIdAndDelete(user._id);
|