繁体   English   中英

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

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

我正在使用findOne找到猫鼬的文档。 我成功地使用doc.set(key, val)将未在架构中定义的属性设置为文档。 但是,当我要检查文档是否具有该属性时,即使文档具有该属性也只是不显示。

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});

架构代码:

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 });

模式是固定的,不是设计动态的。 如果不确定posts将是哪种类型,请将其添加到架构中并使用Mixed类型。

就像是

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