【发布时间】:2020-04-09 08:44:54
【问题描述】:
我正在尝试构建一个基本的 Vue.js Express 配置文件接口,该接口根据与每个用户关联的路由参数 id 返回特定用户的配置文件信息。 Vue.js 中的.get() 请求设置如下:
created () {
let uri = `http://localhost:3000/users/${this.$route.params.id}`;
this.axios.get(uri).then((response) => {
this.profile = response.data;
});
},
Express.js中对应的GET路由设置如下:
// mongodb
const mongo = require('mongodb').MongoClient;
const url = '...'; // connection url
const usersDB = 'users'; // users db name
app.get('/users/:id', function(req, res) {
let id = req.params.id;
var users;
const findUsers = function(db, callback) {
const collection = db.collection('documents');
// no query filter
collection.find({}).sort( {username: 1} )
.toArray(function(err, docs) {
users = docs;
callback(docs);
});
}
mongo.connect(url, function(err, client) {
// assert.equal(null, err);
const db = client.db(usersDB);
findUsers(db, function() {
// send users
res.status(200).send(users);
client.close();
});
});
});
在上面的 Express 路由中,我添加了let id = req.params.id,目的是提示该路由响应基于req.params.id 的特定用户信息。我不确定如何进一步配置此路由以实际返回基于 id 的此类信息。我尝试在路线中实现以下内容:
collection.find({_id: mongo.ObjectId(req.params.id)})
而不是使用:
collection.find({}).sort( {username: 1} )
...但这没有用。知道如何设置此路由以根据req.params.id 返回数据吗?谢谢!
更新的快速路线
// get all users
app.get('/users/:id', function(req, res) {
var o_id = new mongo.ObjectID(req.params.id))
// get all users
var users;
const findUsers = function(db, callback) {
const collection = db.collection('documents');
// no query filter
collection.find({'_id': o_id})
.toArray(function(err, docs) {
users = docs;
callback(docs);
});
}
mongo.connect(url, function(err, client) {
const db = client.db(usersDB);
findUsers(db, function() {
// send users
res.status(200).send(users);
client.close();
});
});
});
【问题讨论】:
标签: javascript node.js mongodb express vue.js