将"_id"转为"id",并删除"__v"字段
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';
import * as toJSON from '@meanie/mongoose-to-json';
export type CatDocument = Cat & Document;
@Schema()
export class Cat {
@Prop()
name: string;
@Prop()
age: number;
@Prop()
breed: string;
}
export const CatSchema = SchemaFactory.createForClass(Cat).plugin(toJSON);
全局使用
MongooseModule.forRoot('mongodb://localhost/test', {
connectionFactory: (connection) => {
connection.plugin(require('@meanie/mongoose-to-json'));
return connection;
},
}),
@Schema()
export class Cat {
@Prop({ required: true })
name: string;
@Prop([Number])
ages: number[];
@Prop({ default: 'lll' })
breed?: string;
@Prop({ type: Date, default: Date.now })
date?: Date;
}
this.catModel.insertMany([{ name: 'aaa', ages: [2, 1] }]);
这将返回:
[
{
"breed": "lll",
"ages": [
2,
1
],
"name": "aaa",
"date": "2021-01-07T02:44:06.459Z",
"id": "5ff67576b9280e2aa0728ee8"
}
]
如果你将date改为number类型,将返回时间戳(毫秒)
@Prop({ type: Number, default: Date.now })
date?: number;
@Schema()
export class Breed {
@Prop()
breed: string;
}
export const BreedSchema = SchemaFactory.createForClass(Breed);
@Schema({versionKey: false})
export class Cat {
@Prop({ required: true })
name: string;
@Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'Breed' })
breed: Breed;
}
export const CatSchema = SchemaFactory.createForClass(Cat);
增:
this.catModel.insertMany([
{
name: 'cat 1',
breed: mongoose.Types.ObjectId('5ff67afda6c7062a2a97575f'),
},
]);
查:
this.catModel.find().populate('breed');
如果一只猫含有多个品种
@Schema({ versionKey: false })
export class Cat {
@Prop({ required: true })
name: string;
@Prop({ type: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Breed' }] })
breed: Breed;
}
// data
{
"_id" : ObjectId("5ff69a49c96ca7d6c68d1b26"),
"name" : "cat 1",
"breed" : ["5ff69995c96ca7d6c68d1b1d", "5ff699b9c96ca7d6c68d1b22"]
}
保存新数据:
const newBreed = new this.breedModel({
breed: 'bbbb',
});
newBreed.save();
return this.catModel.insertMany([
{
name: 'cat 1',
breed: newBreed._id,
},
]);
手机扫一扫
移动阅读更方便
你可能感兴趣的文章