Mongoose没有从mongo

时间:2016-09-19 20:27:23

标签: node.js mongodb mongoose

我正在尝试让Mongoose查询我的mongo实例以获取特定文档(使用_id属性)。我目前有以下路线:

router.get('/document/', function (req, res) {
    var getDocuments = function (callback) {
        var options = { server: { socketOptions: { keepAlive: 1000 } } };
        var connectionString = 'mongodb://user:password@server:27017/db';
        var pID = req.query.id;
        pID = pID.trim();
        console.log(pID);
        var documentArray = [];

        // Connected handler
        Mongoose.connect(connectionString, function (err) {

            var db = Mongoose.connection.useDb('db');
            var pCollection = db.collection("collection");
            //grab all items from pCollection
            pCollection.find({ '_id': pID }, function (error, pDocument) {
                if (error) {
                    console.log(error);
                }
                if (pDocument) {
                    // res.send(JSON.stringify(pDocument));       
                    console.log(pDocument);
                }
                else {
                    console.log("nothing");
                }

            });
            db.close();

        });
    };

    getDocuments(function () {

    });
});

返回的结果不是json文档,似乎没有返回可用值。我究竟做错了什么?在此先感谢您的帮助!

编辑:

我回去后将路线更改为以下内容:

 router.get('/document/', function (req, res) {            
        var pID = req.query.id;

        pID = pID.trim();
        console.log(pID);

        Document.findById(pID, function (error, document) {
            if (error) {
                console.log(error);
            }
            else {
                console.log(document);
            }
        }); 
    });

我还创建了以下模型:

var mongoose = require('mongoose');
var DocumentSchema = require('../schemas/documents');
var Document = mongoose.model('documents', DocumentSchema, 'Documents');
module.exports = Document;

使用以下架构:

var mongoose = require('mongoose');

var DocumentSchema = new mongoose.Schema({       
    documenttPK: String,
    locationID: String,
    docName: String,        
    SerialNumber: String,
    documentID: String,
    dateEntered: Date,
    activeFlag: Boolean
});
module.exports = DocumentSchema;

我的app.js只调用一个db文件:

var mongoose = require('mongoose');
mongoose.connect('mongodb://user:password@server:27017/db');

但结果仍为空。上面的代码有问题吗?

0 个答案:

没有答案