MST

星途 面试题库

面试题:Node.js中如何使用Mongoose连接MongoDB数据库并创建一个简单的Schema

请描述在Node.js项目中,使用Mongoose连接到MongoDB数据库的步骤,并且创建一个表示用户信息的简单Schema,用户信息包含姓名(字符串类型)、年龄(数字类型)。
17.3万 热度难度
前端开发Node.js

知识考点

AI 面试

面试题答案

一键面试
  1. 安装依赖: 在Node.js项目目录下,通过npm安装mongoose库。
    npm install mongoose
    
  2. 连接到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');
    });
    
  3. 创建用户信息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模型,并将其导出供其他模块使用。