【问题标题】:Unable to add parameters that are not defined in mongoose schema无法添加未在 mongoose 架构中定义的参数
【发布时间】:2017-02-03 17:13:43
【问题描述】:

我可以在 mongodb 集合中添加新参数,这些参数未在 mongoose 模式中定义吗? 这是我的架构

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var UsersSchema = new Schema({
    FirstName : {
        type : String       
    },
    LastName : {
        type : String
    },
    ProfileName : {
        type : String
    },
    EmailID : {     //This may actually take Phone Number depending on user account.
        type : String,
        required : true     
    },
    Login : {
        type : { enum : ['Facebook', 'Gmail', 'Custom'] },
        required : true     
    },
    ContactNumber : 
    {
        type : Number
    },
    Address : {  //Add Geo co-ordinates location later.
        type : {}
    },
    ProfilePic : {
        type : String   //URL to image
    },
    Birthday : {
        type : {}      
    },
    Gender : {
        type : { enum : ['Male', 'Female']}
    },
    CreatedDate : {
        type: Date,
        default: Date.now
    },
    ModifiedDate : {
        type: Date,
        default: Date.now       
    },
    LastLogin : {
        type: Date,
        default: Date.now       
    }

});

module.exports = mongoose.model('Users', UsersSchema);

我想添加一些参数,例如 EmailVerifiedMobileNumberVerified 这是我在 mongodb 中实际插入数据的路由代码

router.post('/api/signup',function(req,res){
    console.log("Registering user");

    var user = new Users();
    user.FirstName = req.body.FirstName;
    user.LastName = req.body.LastName;
    user.EmailID = req.body.EmailID;
    user.Login = "Custom";
    user.Password = req.body.Password;
    user.ProfileName = req.body.FirstName + " " +req.body.LastName;
//    user.Birthday = 
    user.Address = req.body.Address;
    user.Gender = req.body.Gender;
    user.EmailVerified = false; // dynamic parameter
    user.MobileNumberVerified = false; // dynamic parameter

//    user.ContactNumber = req.body.ContactNumber;
    user.save(function(err,user){
        if(err){
            console.log(err);
            res.json(err);
        }else{
            console.log("User Registered");
            res.json({result : 1});
        }
    });

});

但在 mongodb 中这些字段不存在。我认为猫鼬不允许动态添加参数。

【问题讨论】:

标签: node.js mongodb express mongoose


【解决方案1】:

不支持在编译模型后向模型架构添加路径。请不要那样做。

【讨论】:

    猜你喜欢
    • 2014-09-14
    • 1970-01-01
    • 2015-04-21
    • 2015-03-22
    • 2017-03-16
    • 1970-01-01
    • 1970-01-01
    • 2012-04-19
    • 1970-01-01
    相关资源
    最近更新 更多