mongodb 无法添加未在mongoose架构中定义的参数

qzwqbdag  于 2023-04-29  发布在  Go
关注(0)|答案(2)|浏览(100)

我可以在mongodb集合中添加mongoose schema中没有定义的新参数吗?下面是我的模式

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这是我的routes代码,它实际上在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中这些字段并不存在。我认为mongoose不允许动态添加参数。

rt4zxlrg

rt4zxlrg1#

不支持在编译模型之后向模型的架构添加路径。请别这样

myzjeezk

myzjeezk2#

Mongoose允许动态添加模式中不存在的参数。但是,默认情况下它是禁用的。
您可以使用**{ strict:false }**当定义模型时。下面的代码。

const thingSchema = new Schema({ /* ... */ }, { strict: false });
const thing = new Thing({ iAmNotInTheSchema: true });
thing.save(); // iAmNotInTheSchema is now saved to the db!!

看看这篇文章。

相关问题