node.js连接mongodb并且增删改查操作
新建config.js
config = {
mongodbUrl: 'mongodb://127.0.0.1:27017/dataobj', // mongodb数据库地址 格式:mongodb://username:password@host:port/name
}
module.exports = config
//引入模块
const mongoose = require('mongoose')
const config = require('./config')
//连接数据库
mongoose.connect(`${config.mongodbUrl}`, {
useNewUrlParser: true,
useUnifiedTopology: true
})
//得到数据库连接句柄
const db = mongoose.connection
//通过数据库连接句柄,监听mongoose数据库成功的事件
db.on('open', function (err) {
if (err) {
console.log('数据库连接失败')
throw err
}
console.log('数据库连接成功')
})
module.exports = {
db
}
// 引入User模型
const User = {
name: String,
email: { type: String, unique: true } // 假设邮箱需要唯一
};
// 创建(增)
function createUser(newUser) {
return User.create(newUser)
.then((createdUser) => {
console.log('User created:', createdUser);
return createdUser;
})
.catch((error) => {
console.error('Error creating user:', error);
throw error;
});
}
// 读取(查)
function getUsers() {
return User.find()
.then((users) => {
console.log('Users found:', users);
return users;
})
.catch((error) => {
console.error('Error finding users:', error);
throw error;
});
}
// 更新(改)
function updateUser(userId, updateData) {
return User.findByIdAndUpdate(userId, updateData, { new: true }) // { new: true } 返回更新后的文档
.then((updatedUser) => {
console.log('User updated:', updatedUser);
return updatedUser;
})
.catch((error) => {
console.error('Error updating user:', error);
throw error;
});
}
// 删除(删)
function deleteUser(userId) {
return User.findByIdAndDelete(userId)
.then((deletedUser) => {
console.log('User deleted:', deletedUser);
return deletedUser;
})
.catch((error) => {
console.error('Error deleting user:', error);
throw error;
});
}
// 示例:使用这些函数
(async () => {
try {
await createUser({ name: 'Alice', email: 'alice@example.com' });
let users = await getUsers();
console.log('Initial users:', users);
const userIdToUpdate = users[0]._id; // 假设我们想更新第一个用户
await updateUser(userIdToUpdate, { name: 'Alicia' });
users = await getUsers(); // 再次获取用户,查看更新结果
console.log('Users after update:', users);
await deleteUser(userIdToUpdate); // 删除该用户
users = await getUsers(); // 最后检查删除结果
console.log('Users after delete:', users);
} catch (error) {
console.error('An error occurred during operations:', error);
} finally {
// 注意:实际应用中,可能需要在适当的时机关闭数据库连接
// mongoose.disconnect();
}
})();