繁体   English   中英

猫鼬发现无法使用ObjectId

[英]Mongoose find not working with ObjectId

我在userref.js中定义了一个架构

module.exports = (function userref() {

    var Schema = mongoose.Schema;

var newSchema= new Schema([{

        userId: {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'User',
            index: true
        },
                value: { type: Number }

    }]);

    var results = mongoose.model('UserRef', newSchema);

    return results;

})();

我插入了一些数据,当我尝试获取一些数据时,我从mongodb控制台获取了正确的值

db.getCollection('userrefs').find({'userId':ObjectId('57a48fa57429b91000e224a6')})

它正确返回一些数据

现在的问题是,当我尝试通过提供objectId来获取代码中的某些数据时,我得到的是空数组。 在下面的函数中,userrefs返回为空数组

//req.params.userId=57a48fa57429b91000e224a6
var UserRef = require('../userref.js');
this.getuserref = function (req, res, next) {

        try {
            var o_userId =mongoose.Types.ObjectId(req.params.userId);
            var query = { userId: o_userId };
            var projection = '_id userId value';

            UserRef.find(query, projection, function (err, usrrefs) {
                if (err) return next(err);
                res.send(usrrefs);
                console.log("userref fetched Properly");
            });
        } catch (err) {
            console.log('Error While Fetching  ' + err);
            return next(err);
        }
    };

另外,当我调试代码时,我可以看到o_​​userId为objectId,id值为垃圾字符

o_userId: ObjectID
_bsontype: "ObjectID"
id: "W¤¥t)¹â$¦"

像这样添加导出

module.exports.modelname= mongoose.model('userrefs', nameofschema, 'userrefs');     

var z = require('../userref.js');

var UserRef  = z.modelname;

现在使用UserRef进行调用。

只需尝试这个人。

Model.find({ 'userId': objectidvariable}, '_id userid etc', function (err, docs) {
      // docs is an array
    });

从他们的官方文档复制的参考样本。

尝试这个:

try {
        var o_userId =mongoose.Types.ObjectId(req.params.userId);
        var query = { userId: o_userId };
        var projection = '_id $.userId $.value';

        UserRef.find(query, projection, function (err, usrrefs) {
            if (err) return next(err);
            res.send(usrrefs);
            console.log("userref fetched Properly");
        });
    } catch (err) {
        console.log('Error While Fetching  ' + err);
        return next(err);
    }

暂无
暂无

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

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