所以我有这个架构。
const Schema = mongoose.Schema;
const Category = new Schema({
name: {
type: String,
index: {
unique: true,
sparse: true
},
validate: [validateProperty, 'Please enter Category Name !']
},
description: {
type: String,
trim: true
},
createdBy: {
type: ObjectId,
ref: "User",
require: true
},
subCatagories: [{
name: {
type: string,
required: true
}
description: {
type: String,
required: true
}
createdBy: {
type: ObjectId,
ref: "User",
require: true
}
}],
updated: {
type: Date
},
created: {
type: Date,
default: Date.now
},
status: {
type: String,
enum: [
'active', 'inactive', 'removed'
],
default: 'active'
}
});
我是否已经创建了这样的类别
const create = ({ Category }) => async (req, res, next) => {
try {
const createdBy = req.user.id
const category = new Category({ createdBy })
_.extend(category , req.body)
await category .save()
return sendCreated(res, { category })
} catch (error) {
next(error)
}
}
然后尝试以这种方式创建新的子类别
const createSubCategory = ({ Category}) => async (req, res, next) => {
try {
const createdBy = req.user.id
const { _id } = req.params
const category= await Category.findOneAndUpdate({ _id })
const subCategory= await category.subCategory.push({ createdBy })
_.extend(subCategory, req.body)
Category.save()
return sendCreated(res, { subCategory})
} catch (error) {
next(error)
}
}
但是似乎没有任何作用...数据库上没有任何更改...我问的是当父文档已经存在时如何创建子文档。
我不确定缺少什么原因,因为我运行了代码,它返回了JSON响应,但推送没有更新数据库