Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
427 views
in Technique[技术] by (71.8m points)

node.js - Node.js Mongoose:同时插入和更新嵌套和非嵌套值(Node.js Mongoose: Inserting and updating a nested and non nested value at the same time)

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 };

Then to save a new fruit... but how do I insert the size a sa child of zest?

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

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();

Then to update the record to add the color to zest withut effecting the size...

(然后更新记录以将颜色添加到皮中,但影响大小...)

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();
    ```
  ask by Bill translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...