簡體   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