本文共 2560 字,大约阅读时间需要 8 分钟。
使用mongoose查询用户数据:
const mongoose = require('mongoose');mongoose.connect('mongodb://localhost/dadi', { useNewUrlParser: true, useUnifiedTopology: true });const UserSchema = mongoose.Schema({ name: String, age: Number, status: Number});const User = mongoose.model('User', UserSchema);// 查询所有用户数据User.find({}, function(err, docs) { if (err) { console.log('查询失败:', err); } else { console.log('查询成功:', docs); }});
新增用户信息:
const user = new User({ name: '张三', age: 30, status: 1});user.save((err, result) => { if (err) { console.error('用户数据存储失败:', err); } else { console.log('用户数据已成功存储:', result); }});
更新特定用户信息:
User.updateOne({ _id: '5f3c002c-aPARTa-XXXX-XXXX-XXXX-XXXXX' }, { name: '张三 updated', age: 35}, (err, result) => { if (err) { console.error('更新失败:', err); } else { console.log('用户信息更新成功:', result); }});
删除特定用户:
User.deleteOne({ _id: '5f3c002c-aPARTa-XXXX-XXXX-XXXX-XXXXX' }, function(err, result) { if (err) { console.error('删除失败:', err); } else { console.log('用户数据已删除:', result); }});
首次操作新闻表(需要手动创建集合):
const mongoose = require('mongoose');mongoose.connect('mongodb://localhost/dadi', { useNewUrlParser: true, useUnifiedTopology: true });const NewsSchema = mongoose.Schema({ title: String, author: String, pic: String, status: Number});const News = mongoose.model('News', NewsSchema, 'news'); // 第三个参数指定集合名
新增一条新闻:
const news = new News({ title: '第一条新闻', author: '管理员', pic: 'news1.jpg', status: 1});news.save((err, result) => { if (err) { console.error('新闻数据存储失败:', err); } else { console.log('新闻数据已成功存储:', result); }});
查询所有新闻:
News.find({}, (err, newsList) => { if (err) { console.log('查询失败:', err); } else { console.log('新闻列表:', newsList); }});
更新特定新闻:
News.updateOne({ _id: '5f3c002c-aPARTb-XXXX-XXXX-XXXX-XXXXX' }, { title: '重要消息更新', author: '管理员 updated'}, (err, result) => { if (err) { console.error('更新失败:', err); } else { console.log('新闻信息更新成功:', result); }});
删除特定新闻:
News.deleteOne({ _id: '5f3c002c-aPARTb-XXXX-XXXX-XXXX-XXXXX' }, (err, result) => { if (err) { console.error('删除失败:', err); } else { console.log('新闻数据已删除:', result); }});
转载地址:http://jqbgz.baihongyu.com/