简体   繁体   English

如何在 mongodb 中存储空数组

[英]How to store empty array in mongodb

I want to store empty array in user schema's friends key.我想将空数组存储在用户模式的朋友键中。 But, mongoose won't let me to add empty array of friends.但是,mongoose 不会让我添加空的朋友数组。

Here's my User schema这是我的用户架构

const userSchema = mongoose.Schema({
  firstName: {
    type: String,
    required: true,
  },
  lastName: {
    type: String,
    required: true,
  },
  userName: {
    type: String,
    unique: true,
    required: true,
  },
  email: {
    type: String,
    required: true,
    unique: true,
    validate: [validator.isEmail, "Please enter a valid Email"],
  },
  password: {
    type: String,
    required: true,
    minlength: [6, "Password must be at least 6 characters"],
  },
  friends: [
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'User'
      unique: true,
    },
  ],
});

And here's my code to pull data from array and save empty array这是我从数组中提取数据并保存空数组的代码

const index = req.user.friends.findIndex(friend => friend.toString() === req.params.id);
  
  if(index !== -1){
    req.user.friends.splice(index, 1);
  }else{ 
    req.user.friends.push(req.params.id);
  }

    const user = new User(req.user);

    await user.save({validateBeforeSave: false});
    return res.json({success: true});

specify default value instead改为指定默认值

friends: [
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'User'
      unique: true,
      default: []
    },
  ],

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM