首页 > 解决方案 > 使用 mongoose 在 mongodb 中 findOne 结果返回集合的空值

问题描述

当我运行此代码时 - 它输出 null

Card.findOne({userId : model.userId} , function (err, cardData) {
        console.log(err); //output null
        console.log(cardData); //output null
    });

如果卡存在且 cardData 则预期输出 null

控制台日志(错误);//输出空

控制台.log(cardData); //输出cardData {json 格式}

样本文件

{
    "_id" : ObjectId("5b32712d90bd3e000454ce92"),
    "reactions" : {
        "likes" : [],
        "disLikes" : [],
        "comments" : []
    },
    "code" : "1qf28",
    "creationDate" : ISODate("2018-06-26T17:00:29.542Z"),
    "reports" : [],
    "userId" : "5b2bee8c47ca27344f5425cf",
    "name" : "Ahmed Mohsen",
    "phone" : "01233556",
    "gender" : "male",
    "public" : true,
    "position" : "Developer ",
    "subtitle" : "Free costa",
    "img" : "https://i.imgur.com/2qLGIWa.jpg",
    "__v" : 0
}

更新

userId 未定义

但是我发送它-通过此代码

axios.get(settings.default.baseUrl + '/api/cards/check_user_card' , {userId : userId})

标签: node.jsmongodbexpressmongoose

解决方案


试试这个代码:

var ObjectId = require('mongoose').Types.ObjectId;
Card.findOne({userId : new ObjectId(model.userId)} , function (err, cardData) {
    console.log(err); //output null
    console.log(cardData); //output null
});

推荐阅读