将mongoose字符串模式类型的默认值设置为空白,并使该字段可选

时间:2016-12-08 07:16:19

标签: node.js mongodb mongoose schema

我在nodejs中有一个带有mongoose的测试模式,比如

public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {

    private ArrayList<Movie> movies;
    private Context context;

    public DataAdapter(Context context, ArrayList<Movie> movies) {
        this.movies = movies;
        this.context = context;
    }

    public void addItems(ArrayList<Movie> movies) {

        this.movies.addAll(movies);

    }

    @Override
    public DataAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recycler_view_grid_item, viewGroup, false);

        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(DataAdapter.ViewHolder viewHolder, int i) {

        viewHolder.title.setText(movies.get(i).getTitle());
        Picasso.with(context).load(movies.get(i).getImage_url_medium()).placeholder(R.drawable.placeholder).into(viewHolder.thumbnail);
    }

    @Override
    public int getItemCount() {
        return movies.size();
    }



    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        private TextView title;
        private ImageView thumbnail;

        public ViewHolder(View view) {
            super(view);

            title = (TextView) view.findViewById(R.id.title);
            thumbnail = (ImageView) view.findViewById(R.id.thumbnail);
            view.setOnClickListener(this);
        }

        // Handles the row being being clicked
        @Override
        public void onClick(View view) {
            int position = getAdapterPosition(); // gets item position
            if (position != RecyclerView.NO_POSITION) { // Check if an item was deleted, but the user clicked it before the UI removed it
                Movie movie = movies.get(position);
                // start detail activity
                Intent i = new Intent(context, MovieDetail.class);
                i.putExtra(Constants.MOVIES_OBJECT, movie);
                context.startActivity(i);
            }
        }
    }


}

如何将类别字段设为可选,如果未由用户提供,则将其设为空白?

我试过

testschema = mongoose.Schema({
         name:{
    type:String,
    required:true,
    unique:true
  },
  image:{
    type:String,
    required:true
  },
  category:{
    type:String
  },
});

但是当打印出使用该方案保存的文档时,它甚至不会显示字段类别。

2 个答案:

答案 0 :(得分:12)

您最需要的是default值设置。

category: {
    type: String,
    default: ''
}

这会使该字段有些可选,因为如果您不设置它,则默认为''

答案 1 :(得分:0)

克服当前对新插入内容的限制的另一种方法是在执行发布请求时放置默认值。如以下示例代码所示:

var category = req.body.category || 0;

假设用户未触摸该字段,因此默认情况下其值为