简体   繁体   English

检查mongodb文档是否具有架构中未定义的属性?

[英]Check if mongodb document has a property that isn't defined in schema?

I am finding a document with mongoose using findOne . 我正在使用findOne找到猫鼬的文档。 I succeded in setting a property, that is not defined in the schema, to the document using doc.set(key, val) . 我成功地使用doc.set(key, val)将未在架构中定义的属性设置为文档。 However when I want to check if the document has that property or not, it just shows no even if the document has it. 但是,当我要检查文档是否具有该属性时,即使文档具有该属性也只是不显示。

User.findOne({email: req.user.email})
    .then(user=>{
        if(user.posts){
            //Tried with user.has("posts")=>logs error: .has is not a function
            let posts = user.get("posts");
            posts.push({
                    "Type": "Idea",
                    "Field/s of idea": req.body["Field/s of idea"],
                    "Idea": req.body.idea,
                    "Date": new Date()
                    });
            user.set("posts", posts);
        }else{
            user.set("posts", [{
                    "Type": "Idea",
                    "Field/s of idea": req.body["Field/s of idea"],
                    "Idea": req.body.idea,
                    "Date": new Date()
                    }]
            );
        };
        user.save();
    })
    .catch(err=>{throw err});

Schema code: 架构代码:

const UserSchema = new Schema({
    _id: {type: ObjectId, auto: true},
    username: {type: String, required: true, max:18},
    email: {type: String, required: true},
    password: {type: String, required: true, min:5},
    date_of_registration: {type: Date, required: true}
}, { strict: false });

Schemas are fixed and not dynamic by design. 模式是固定的,不是设计动态的。 If you are unsure about what type posts will be, add it to your schema and use the Mixed type. 如果不确定posts将是哪种类型,请将其添加到架构中并使用Mixed类型。

Something like 就像是

const UserSchema = new Schema({
    ...
    posts: [ { type: Mixed, required: false } ]
}, { strict: false });

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

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