简体   繁体   English

Mongoose 从子架构中删除键(嵌套子文档)

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

I have two schemas defined, imageSchema and userSchema.我定义了两个模式,imageSchema 和 userSchema。 imageSchema has key postedBy: userSchema. imageSchema 有关键发布者:userSchema。 Question is shall I remove unused attributes of userSchema (like password) when nested into imageSchema, if so how to do it?问题是我应该在嵌套到 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")
          })
...

So after I created a new document of Image, I checked the database, the user field of the new Image has the attribute of password, which is not desired.所以在我创建了一个Image的新文档后,我检查了数据库,新Image的用户字段具有密码属性,这是不需要的。 "delete user.password" seems not working. “删除 user.password”似乎不起作用。 How should I delete this attribute?我应该如何删除这个属性? Shall I do it when defining the imageSchema, or remove it when posting the data (the app.post part)?我应该在定义 imageSchema 时这样做,还是在发布数据时删除它(app.post 部分)?

This can be done is multiple ways.这可以通过多种方式完成。 The way i like is to exclude the field from schema and also exclude while insertion.我喜欢的方式是从模式中排除该字段,并在插入时排除。

Exclude from schema从架构中排除

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

Exclude while inserting插入时排除

we are omitting the user here before insertion this can be also done with underscore/lodash _.omit(user, 'password')我们在插入之前在这里省略了用户这也可以用下划线/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