0

以下是基本的用户配置文件架构

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
    const userprofileSchema = new Schema({
        name:{type:String},
        userId: { type: Number, required: true },
        userName: { type: String, require: true },
        avatarUrl: {type:String , default:'https://i.stack.imgur.com/dH5Lm.jpg'},
        bio:{type:String},
        url: String
    })

    module.exports = mongoose.model("userprofile",userprofileSchema); 

以下是存储在 mongodb 中的文档:

 {  
    "avatarUrl": "avatarurl",
    "_id": "5edd2dfc7c213e044cc2783b",
    "userId": "1000",
    "name": "Sandeep Patel",
    "userName": "cs-dev",
    "url": "portfolioUrl",
    "bio": "Work in progress!"
    }

现在,当我这样做时,userPofile.findOne({userName:"value"}}它会给我结果,但如果我在数字字段上做同样的事情,即userPofile.findOne({userId:value}}结果为空。我检查了很多次。我错过了什么吗?

猫鼬版本:5.9.18

mongod 版本:3.6.12 (MMAPv1)

4

1 回答 1

1

我刚刚尝试在我的 node.js 应用程序上重现相同的问题,但 findOne 也适用于数字字段。

从您在问题中粘贴的 mongoDB 文档中,您的 Number 字段似乎被存储为字符串。

它应该是这样的:

    {  
    "avatarUrl": "avatarurl",
    "_id": "5edd2dfc7c213e044cc2783b",
    "userId": 1000, (Notice the lack of double quotes here)
    "name": "Sandeep Patel",
    "userName": "cs-dev",
    "url": "portfolioUrl",
    "bio": "Work in progress!"
    }

在这之后,

userPofile.findOne({userId:1000}}作品

因此,您可能需要在插入数据库时​​对变量进行类型转换。

于 2020-06-08T00:32:01.357 回答