Node.js猫鼬:同时插入和更新嵌套和非嵌套值

时间:2019-12-03 10:24:00

标签: node.js mongodb mongoose

import * as mongoose from 'mongoose';
import { Document, Schema } from 'mongoose';

interface UserModelInterface extends Document {
  fruit: string
  zest: {
    color: string;
    size: string;
  };
}

const userSchema: Schema = new Schema(
  {
    fruit: { type: String },
    zest: {
      color: { type: String },
      size: { type: String },
    },
  },
  {
    timestamps: true,
  }
);

const userModel = mongoose.model<UserModelInterface>('User', userSchema);
export { userModel, UserModelInterface };

然后保存新的水果...但是我如何插入一个热情的孩子的大小?

import { userModel, UserModelInterface } from '../models/user';
...
const fruit = 'Pinapple';
const size = 'Large';
const user = new userModel({
  fruit,
  zest: {size}                     //<== Somthings wrong here?
} as UserModelInterface);
const saved = await user.save();

然后更新记录以将颜色添加到皮肤中,而不会影响大小...

import { userModel, UserModelInterface } from '../models/user';
...
const fruit = 'Pinapple';
const color = 'Golden';
const confirmed = await userModel
  .findOneAndUpdate(
    { fruit },
    {
      $set: { zest: {color} },    //<== Somthings wrong here?

    }
  )
  .exec();
    ```

0 个答案:

没有答案