簡體   English   中英

Mongoose 從子架構中刪除鍵(嵌套子文檔)

[英]Mongoose Remove key(s) from child schema (nested subdocuments)

我定義了兩個模式,imageSchema 和 userSchema。 imageSchema 有關鍵發布者:userSchema。 問題是我應該在嵌套到 imageSchema 時刪除 userSchema 的未使用屬性(如密碼),如果是的話怎么做?

var userSchema = new mongoose.Schema({
  email: String,
  password: String,
  name: String,
}, {versionKey: false})

var imageSchema = new mongoose.Schema({
  filePath: String,
  user: userSchema,
  createdAt: Date,
  comments: [{body: "String", by: mongoose.Schema.Types.ObjectId}]
})
...
app.post("/upload-image", async function(req, res){
  if(req.session.user_id) {
    ...
      fileSystem.rename(oldPath, newPath, function(err2){
        getUser(req.session.user_id, function(user){
          delete user.password
          var currentTime = new Date().getTime()
          Image.create({
            "filePath": newPath,
            "user": user,
            "createdAt": currentTime,
            "comments": []
          }, function(err2, data){
            res.redirect("/?message=image_uploaded")
          })
...

所以在我創建了一個Image的新文檔后,我檢查了數據庫,新Image的用戶字段具有密碼屬性,這是不需要的。 “刪除 user.password”似乎不起作用。 我應該如何刪除這個屬性? 我應該在定義 imageSchema 時這樣做,還是在發布數據時刪除它(app.post 部分)?

這可以通過多種方式完成。 我喜歡的方式是從模式中排除該字段,並在插入時排除。

從架構中排除

var imageSchema = new mongoose.Schema({
  filePath: String,
  user: userSchema.pick(["email", "name"]), // this will return schema with only email and name from the schema
  createdAt: Date,
  comments: [{body: "String", by: mongoose.Schema.Types.ObjectId}]
})

插入時排除

我們在插入之前在這里省略了用戶這也可以用下划線/lodash _.omit(user, 'password')

getUser(req.session.user_id, function({password, ...user}){
         Image.create({
            "filePath": newPath,
            "user": user,
            "createdAt": Date.now(),
            "comments": []
          })
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM