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

时间:2019-06-03 19:33:54

标签: node.js mongodb express mongoose

我正在使用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 });

1 个答案:

答案 0 :(得分:2)

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

类似

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