Как выбрать элемент в mongodb по id из get параметров?
Не подставляет get переменную в объект, передаваемый в findOne. Если просто вставляю { id: 2 } или let id = 2 и { id: id }, база возвращает нужный элемент. Мой ключ id существует наряду с встроенным _id, поиск веду именно по первому. Как передать в базу get переменную?
const express = require("express");
const app = express();
const MongoClient = require('mongodb').MongoClient;
const objectId = require("mongodb").ObjectID;
const cors = require('cors');
const mongoClient = new MongoClient("mongodb://localhost:27017/", { useNewUrlParser: true });
// Connection URL
app.use(cors());
app.options('*', cors());
mongoClient.connect(function(err, client){
if(err) return console.log(err);
dbClient = client;
app.locals.db = client.db("socialNetwork");
app.listen(3002, function(){
console.log('go');
});
});
app.get("/users", (req, res) => {
const collection = req.app.locals.db.collection("users");
const id = req.query.id;
if(id) {
collection.findOne({id: id}, function(err, user){
if(err) return console.log(err);
res.send(user);
});
}else {
collection.find({}, {_id:0}).toArray(function(err, users){
if(err) return console.log(err);
res.send(users)
});
}
});
process.on("SIGINT", () => {
dbClient.close();
process.exit();
});
"_id": {
"$oid": "5ec3e670a474c579cc6e3d81"
},
"name": "Alexander Tonkonog",
"avatar": "https://www.gravatar.com/avatar/cdcfcdf8989e433a230201c171b6eb08?s=58&r=g&d=mm",
"friends": [2],
"id": 1,
"active": "26.02.20 20:52",
"tag": ["Popular"],
"type": "user",
"follow": [1, 2],
"data": {
"birthday": "29.08.1997",
"city": "Krasnodar",
"sex": "male",
"education": "KubSU",
"family": null,
"language": ["Russian", "English"]
}
Ответы (2 шт):
Автор решения: Александр
→ Ссылка
const express = require("express");
const app = express();
const MongoClient = require('mongodb').MongoClient;
const objectId = require("mongodb").ObjectID;
const cors = require('cors');
const mongoClient = new MongoClient("mongodb://localhost:27017/", { useNewUrlParser: true });
// Connection URL
app.use(cors());
app.options('*', cors());
mongoClient.connect(function (err, client) {
if (err) return console.log(err);
dbClient = client;
app.locals.db = client.db("socialNetwork");
app.listen(3002, function () {
console.log('go');
});
});
app.get("/users", async (req, res) => {
const collection = req.app.locals.db.collection("users");
const id = req.params.id;
if (id) {
try {
const user = await collection.findOne({ _id: id }) // вот тут поменяйте на _id
res.send(user);
} catch (e) {
console.log(e.message)
}
} else {
try {
const users = await collection.find()
res.send(users)
} catch (e) {
console.log(e.message)
}
}
});
process.on("SIGINT", () => {
dbClient.close();
process.exit();
});
Автор решения: Александр Тонконог
→ Ссылка
по какой-то причине, пакет mongodb для node js не может искать через find по id (в консоли можно искать как по _id, так и по id).