我有一个模型,在第一次POST后不断出错.我正在创建一个X天的调度应用程序,包括房间和房间的时间段.
我遇到的问题是在数据库中创建Day Objects.为了便于阅读,我将只有一个键值对
day.model.js
var mongoose = require('mongoose');
// Day Schema
var daySchema = mongoose.Schema({
name:{
type: String,
required: true,
},
createdAt:{
type: Date,
default: Date.now
}
});
var Day = module.exports = mongoose.model('Day', daySchema);
// Get all Days
module.exports.getDays = function(callback, limit){
Day.find(callback).limit();
};
// Add Day
module.exports.addDay = function(day, callback){
var add = {
name: day.name,
};
Day.create(add, callback);
};
Run Code Online (Sandbox Code Playgroud)
day.routes.js
var express = require('express');
var router = express.Router();
var jwt = require('jsonwebtoken');
var config = require('../config/database');
Day …Run Code Online (Sandbox Code Playgroud) 我正在设计一个 Web 应用程序,用于管理母公司和子公司的组织结构。有两种类型的公司:1-主公司,2-子公司。公司只能属于一个公司,但可以有几个子公司。我的猫鼬架构如下所示:
var companySchema = new mongoose.Schema({
companyName: {
type: String,
required: true
},
estimatedAnnualEarnings: {
type: Number,
required: true
},
companyChildren: [{type: mongoose.Schema.Types.ObjectId, ref: 'Company'}],
companyType: {type: String, enum: ['Main', 'Subsidiary']}
})
module.exports = mongoose.model('Company', companySchema);
Run Code Online (Sandbox Code Playgroud)
我将所有公司存储在一个集合中,每个公司都有一个数组,其中包含对其子公司的引用。然后我想将所有公司显示为一棵树(在客户端)。我想查询所有填充他们的孩子的主要公司,以及无限的嵌套级别。我怎样才能做到这一点?或者也许你知道更好的方法。我还需要能够查看、添加、编辑、删除任何公司。
现在我有这个:
router.get('/companies', function(req, res) {
Company.find({companyType: 'Main'}).populate({path: 'companyChildren'}).exec(function(err, list) {
if(err) {
console.log(err);
} else {
res.send(list);
}
})
});
Run Code Online (Sandbox Code Playgroud)
但它只填充一个嵌套级别。我感谢任何帮助
我有几个架构:
var parentSchema = new Schema({name: String});
var childSchema = new Schema({
name: String,
parent: {type: Schema.ObjectId, ref: 'Parent'}
});
Run Code Online (Sandbox Code Playgroud)
我希望能够调用Child.find().populate('parent')然后使用以下虚拟 getter:
childSchema.virtual('url').get(function () {
return "/" + this.parent.name + "/" + this.name
});
Run Code Online (Sandbox Code Playgroud)
但是,当我调用find().populate(),然后将结果子项传递给我的视图并尝试使用时child.url,我总是parent.name设置为未定义。我究竟做错了什么?
我有这个猫鼬模式:
const User = mongoose.model('User', new Schema({
id: String,
name: String,
extra: { bb: Number, chain: Number }
}), 'users');
Run Code Online (Sandbox Code Playgroud)
当我看到一个 new 时User,它是这样存储的:
{
_id: ...,
id: '1234',
name: 'John',
extra: {
_id: ...,
bb: 54,
chain: 7
},
__v: 1
}
Run Code Online (Sandbox Code Playgroud)
如您所见,Mongoose(或 Mongo,我不知道)_id在嵌入对象中包含了一个extra。为什么会这样?我怎样才能防止它发生?
我想用 mongoose 作为 JSON 对象将一个对象填充到一个虚拟字段中,但它总是返回一个包含单个项目的数组。
这是我的方案代码(部分带有虚拟字段):
Order.virtual('client', {
type: 'ObjectId',
ref: 'User',
localField: 'clientId',
foreignField: '_id'
});
Run Code Online (Sandbox Code Playgroud)
这是我如何做人口:
Order.findOneAndUpdate({ internalStatus: 2}, { internalStatus: 3 })
.lean()
.populate({ path: 'client', select: 'email' })
.exec(function (err, order) {
//...
});
Run Code Online (Sandbox Code Playgroud)
这是我在返回的 JSON 中收到的内容:
{ _id: 5ad903d90443fe13b8c9061a,
client: [ { _id: 5b3755fe69635d1e942d00a8, email: 'user@user.com' } ] }
Run Code Online (Sandbox Code Playgroud)
这就是我想要实现的目标:
{ _id: 5ad903d90443fe13b8c9061a,
client: { _id: 5b3755fe69635d1e942d00a8, email: 'user@user.com' } }
Run Code Online (Sandbox Code Playgroud)
感谢您的任何帮助或建议!
根据猫鼬内置验证器文档,我可以使用条件必填字段:
const schema = mongoose.Schema({
a: {
type: String,
required: function () {
return this.b === 1
}
},
b: {
type: Number,
required: true
}
});
Run Code Online (Sandbox Code Playgroud)
在此模式中,a仅当 propertyb等于时才需要该属性1。
尝试创建新文档按预期工作:
Model.create({ b: 1 }); // throws ValidationError (property a is required)
Run Code Online (Sandbox Code Playgroud)
和
Model.create({ b: 2 }); // creates document
Run Code Online (Sandbox Code Playgroud)
我的问题是尝试更新现有文档并将属性设置b为1因此a应该需要属性。
运行以下代码:
Model.findByIdAndUpdate(model._id, { b: 1 }, { new: true, runValidators: true});
Run Code Online (Sandbox Code Playgroud)
意外更新文档而不会抛出a需要属性的错误。
我的猜测是验证仅针对更新的属性(property b …
我正在处理一个项目,在该项目中,我需要在一个模型中根据另一个字段值设置一个字段的值。让我用一些代码解释一下。
Destination model
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const DestinationSchema = new Schema({
name: {
type: String,
required: true
},
priority: {
type: Number,
default: 0,
max: 10,
required: true
}
})
DestinationSchema.statics.getPriority = function(value) {
return this.findOne({ _id: value })
}
const Destination = mongoose.model('Destination', DestinationSchema)
exports.Destination = Destination
Run Code Online (Sandbox Code Playgroud)
Task model
const mongoose = require('mongoose')
const { Destination } = require('../_models/destination.model')
const Schema = mongoose.Schema;
const TaskSchema = new Schema({
priority: {
type: Number,
required: true, …Run Code Online (Sandbox Code Playgroud) 我有一个模型:
const comment = new mongoose.Schema({
id: { type: ObjectId, required: true },
comment: { type: String },
replies: [comment]
});
Run Code Online (Sandbox Code Playgroud)
想要创建这样的文档:
{
"id": 1,
"comment": "Grand Parent Comment",
"replies": [
{
"id": 11,
"comment": "Parent Comment",
"replies": [
{
"id": 111,
"comment": "Comment",
"replies": [
{
"id": 1111,
"comment": "Child Comment",
"replies": []
}
]
},
{
"id": 112,
"comment": "Sibling Comment",
"replies": []
}
]
}
]
}
Run Code Online (Sandbox Code Playgroud)
根据这个答案的回答
this只需作为模型的参考即可解决。
{
"id": 1,
"comment": "Grand Parent …Run Code Online (Sandbox Code Playgroud) nestjs/mongoose我正在尝试使用以下类中的装饰器创建 Mongo 模式:
@Schema()
export class Constraint {
@Prop()
reason: string;
@Prop()
status: Status;
@Prop()
time: number;
}
Run Code Online (Sandbox Code Playgroud)
问题Status定义如下:
export type Status = boolean | 'pending';
Run Code Online (Sandbox Code Playgroud)
我无法弄清楚要传递给status'sprop装饰器的内容,因为我收到以下错误:
Error: Cannot determine a type for the "Constraint.status" field (union/intersection/ambiguous type was used). Make sure your property is decorated with a "@Prop({ type: TYPE_HERE })" decorator
Run Code Online (Sandbox Code Playgroud)
并且{ type: Status }不起作用,因为Status是 atype而不是 a Class。
_id在我的嵌套应用程序中,我在调用时遇到类型错误user,因为猫鼬自动定义了_id,因此它不存在于我的模式中,该模式被定义为承诺的类型。
当承诺类型更改为任何类似类型Promise<any>时,就不会出现类型错误。
async create(createUserDto: CreateUserDto): Promise<User> {
const createdUser = await new this.userModel(createUserDto).save();
return createdUser;
}
Run Code Online (Sandbox Code Playgroud)
但我想知道这是正确的方法还是我应该做其他事情。
我不想_id在架构中定义来解决这个问题。
@Prop({ auto: true})
_id!: mongoose.Types.ObjectId;
Run Code Online (Sandbox Code Playgroud)
用户架构.ts
// all the imports here....
export type UserDocument = User & Document;
@Schema({ timestamps: true })
export class User {
@Prop({ required: true, unique: true, lowercase: true })
email: string;
@Prop()
password: string;
}
export const UserSchema = SchemaFactory.createForClass(User);
Run Code Online (Sandbox Code Playgroud)
用户.controller.ts
@Controller('users')
@TransformUserResponse(UserResponseDto)
export class UsersController {
constructor(private …Run Code Online (Sandbox Code Playgroud) mongoose-schema ×10
mongoose ×8
mongodb ×7
node.js ×6
typescript ×3
nestjs ×2
express ×1
javascript ×1