面试题答案
一键面试- 安装依赖:
在Node.js项目目录下,通过npm安装
mongoose
库。npm install mongoose
- 连接到MongoDB数据库:
在项目的JavaScript文件(例如
server.js
)中编写以下代码:const mongoose = require('mongoose'); // 连接字符串,假设MongoDB运行在本地默认端口27017,数据库名为test const uri ='mongodb://127.0.0.1:27017/test'; mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true }); const db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); db.once('open', function () { console.log('Connected to MongoDB'); });
- 创建用户信息Schema:
继续在上述文件或单独的
user.js
文件中编写:const mongoose = require('mongoose'); const userSchema = new mongoose.Schema({ name: { type: String }, age: { type: Number } }); const User = mongoose.model('User', userSchema); module.exports = User;
上述代码首先安装了mongoose
库,然后使用mongoose.connect
连接到MongoDB数据库,并处理连接的错误和成功事件。接着定义了一个userSchema
,包含name
(字符串类型)和age
(数字类型)字段,最后通过mongoose.model
创建了一个User
模型,并将其导出供其他模块使用。