繁体   English   中英

NodeJS + MongoDB:使用 findOne() 从集合中获取数据

[英]NodeJS + MongoDB: Getting data from collection with findOne ()

我有一个包含多个对象的“公司”集合。 每个对象都有“_id”参数。 我正在尝试从 db 获取此参数:

app.get('/companies/:id',function(req,res){
db.collection("companies",function(err,collection){
    console.log(req.params.id);
    collection.findOne({_id: req.params.id},function(err, doc) {
        if (doc){
            console.log(doc._id);
        } else {
            console.log('no data for this company');
        }
    });
});
});

因此,我请求公司/4fcfd7f246e1464d05000001(4fcfd7f246e1464d05000001 是我需要的对象的 _id-parma)并且 findOne 什么都不返回,这就是为什么 console.log('no data for this company'); 执行。

我绝对确定我有一个 _id="4fcfd7f246e1464d05000001" 的对象。 我做错了什么? 谢谢!

但是,我刚刚注意到 id 不是典型的字符串字段。 这就是 mViewer 显示的内容:

"_id": {
        "$oid": "4fcfd7f246e1464d05000001"
    },

好像有点奇怪……

您需要构造 ObjectID 而不是将其作为字符串传入。 这样的事情应该工作:

var BSON = require('mongodb').BSONPure;
var obj_id = BSON.ObjectID.createFromHexString("4fcfd7f246e1464d05000001");

然后,尝试在您的 find/findOne 中使用它。

编辑:正如Ohad在评论中指出的(感谢 Ohad!),您还可以使用:

new require('mongodb').ObjectID(req.params.id)

而不是上面概述的createFromHexString

那是因为 mongo 中的_id字段不是string类型(如您的req.params.id )。 正如其他答案中所建议的那样,您应该明确转换它。

试试mongoskin ,你可以像 node-mongodb-native 驱动程序一样使用它,但要加点糖。 例如:

// connect easier
var db = require('mongoskin').mongo.db('localhost:27017/testdb?auto_reconnect');

// collections
var companies = db.collection('companies');

// create object IDs
var oid = db.companies.id(req.params.id);

// some nice functions…
companies.findById();

//… and bindings
db.bind('companies', {
  top10: function(callback) {
    this.find({}, {limit: 10, sort: [['rating', -1]]).toArray(callback);
  } 
});

db.companies.top10(printTop10);

您可以使用findById()它将为您处理 id 转换。

company = Company.findById(req.params.id, function(err, company) {
    //////////
});

如果这些对您不起作用,这对我访问博客文章有用:

const getSinglePost = async (req, res) => {

    let id = req.params.id;
    var ObjectId = require('mongodb').ObjectId;
    const db = await client.db('CMS');

    const data = await db.collection("posts").findOne({ _id: ObjectId(id) })

    if (data) {
        res.status(200).send(data)
    } else res.status(400).send({ message: "no post found" })

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM