【发布时间】:2018-05-21 08:53:58
【问题描述】:
有可能我只是精疲力尽,但我有以下型号:
用户
const mongoose = require('mongoose');
const validate = require('mongoose-validator');
const Post = require('./post');
let UserSchema = mongoose.Schema({
firstName: { type: String, required: true },
lastName: { type: String, required: true },
email: {
type: String, required: true, lowercase: true, trim: true, unique: true, index: true,
validate: [validate({ validator: 'isEmail', message: 'Invalid Email!' })]
},
posts: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Post' }]
})
module.exports = mongoose.model('User', UserSchema);
帖子
const _ = require('lodash');
const mongoose = require('mongoose');
const User = require('./user');
let PostSchema = mongoose.Schema({
user: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
title: { type: String, required: true },
body: { type: String, require: true }
})
PostSchema.post('save', async function (next) {
await User.update({ _id: this.user }, { $push: { posts: this._id } })
return next();
})
module.exports = mongoose.model('Post', PostSchema);
尝试添加新帖子时,帖子保存挂钩运行,但我收到错误 User.update is not a function(findOneAndUpdate、findOne 等也是如此)。
我可以毫无问题地从应用程序的其余部分调用 user.update,所以不确定这里发生了什么。两个模型都在同一个目录中。
【问题讨论】:
-
小观察,但无论如何都不需要维护数组。您已经在帖子中有用户 id 值,并且可以简单地在
User上使用“虚拟”(或者只是不要打扰并使用$lookupalways )而不是保留一个数组。另请注意,无论如何您可能应该嵌入 9/10 次。 stackoverflow 上甚至没有一个答案,这会导致 MongoDB 中的嵌入细节实际上违反 16MB BSON 限制。只是出于好奇,如果您删除 async/await 甚至 next 以使其成为串行操作,会发生什么? -
使用回调而不是异步的结果相同,你的想法可能更好,但现在这让我很困扰,我需要找出原因:D
标签: node.js mongodb mongoose model