Node.js Mongoose-中间件中未找到模型方法
有可能我已经筋疲力尽了,但我有以下几种型号: 使用者 职位 当尝试添加新帖子时,post保存钩子会运行,但我得到的错误是User.update不是一个函数(findOneAndUpdate、findOne等也是如此)Node.js Mongoose-中间件中未找到模型方法,node.js,mongodb,mongoose,model,Node.js,Mongodb,Mongoose,Model,有可能我已经筋疲力尽了,但我有以下几种型号: 使用者 职位 当尝试添加新帖子时,post保存钩子会运行,但我得到的错误是User.update不是一个函数(findOneAndUpdate、findOne等也是如此) 我可以从应用程序的其余部分调用user.update而不会出现问题,因此不确定这里发生了什么。两个模型都在同一个目录中。您遗漏的是post中间件的第一个参数是“文档”,而不是下一个处理程序: user.js post.js index.js 返回: Mongoose: users.
我可以从应用程序的其余部分调用user.update而不会出现问题,因此不确定这里发生了什么。两个模型都在同一个目录中。您遗漏的是
post
中间件的第一个参数是“文档”,而不是下一个处理程序:
user.js
post.js
index.js
返回:
Mongoose: users.remove({}, {})
Mongoose: posts.remove({}, {})
Mongoose: users.insertOne({ posts: [], _id: ObjectId("5b0217001b5a55208150cc9b"), firstName: 'Ted', lastName: 'Logan', __v: 0 })
Mongoose: posts.insertOne({ _id: ObjectId("5b0217001b5a55208150cc9c"), user: ObjectId("5b0217001b5a55208150cc9b"), title: 'Hi', body: 'Whoa!', __v: 0 })
Mongoose: users.update({ _id: ObjectId("5b0217001b5a55208150cc9b") }, { '$push': { posts: ObjectId("5b0217001b5a55208150cc9c") } }, {})
显示更新以正确的细节触发
在良好的设计中,您确实应该避免这种情况,只需从用户
模型中删除posts
数组即可。您可以始终使用以下选项之一:
或者通过以下方式获取数据:
“在父对象上”存储和维护相关ObjectId
值的数组有点“反模式”,会导致不必要的开销,例如在两个地方写入,而您只需要“一个”
一般来说,您应该选择嵌入“first”,并且仅在应用程序的使用模式实际需要时才考虑“reference”。简单地使用数据库引擎复制RDBMS的相同模式并不是利用它的最佳方式。观察不多,但实际上不需要维护阵列。您在帖子中已经有了用户id值,只需在用户
上使用一个“虚拟”(或者不用麻烦,总是使用$lookup
),而不用保留数组。还要注意的是,9/10次您可能无论如何都应该嵌入。对于stackoverflow,甚至没有一个答案会导致MongoDB中的嵌入细节实际违反16MB BSON限制。不过,出于好奇,如果您删除async/Wait,甚至下一个,使其成为一个串行操作,会发生什么?使用回调而不是async会产生相同的结果,您的想法可能更好,但现在这让我感到困扰,我需要找出原因:先生,我向您提示我的fez!我真的一定是疯了。
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);
const { Schema } = mongoose = require('mongoose');
const userSchema = new Schema({
firstName: String,
lastName: String,
posts: [{ type: Schema.Types.ObjectId, ref: 'Post' }]
});
const { Schema } = mongoose = require('mongoose');
const User = require('./user');
const postSchema = new Schema({
user: { type: Schema.Types.ObjectId, ref: 'User' },
title: String,
body: String
});
// note that first argument is the "document" as in "post" once it was created
postSchema.post('save', async function(doc, next) {
await User.update({ _id: doc.user._id },{ $push: { posts: doc._id } });
next();
});
const { Schema } = mongoose = require('mongoose');
const User = require('./user');
const Post = require('./post');
const uri = 'mongodb://localhost/posttest';
mongoose.set('debug', true);
mongoose.Promise = global.Promise;
const log = data => console.log(JSON.stringify(data, undefined, 2));
(async function() {
try {
const conn = await mongoose.connect(uri);
await Promise.all(Object.entries(conn.models).map(([k,m]) => m.remove()));
let user = await User.create({ firstName: 'Ted', lastName: 'Logan' });
let post = new Post({ user: user._id, title: 'Hi', body: 'Whoa!' });
post = await post.save();
mongoose.disconnect();
} catch(e) {
console.error(e)
} finally {
process.exit()
}
})()
Mongoose: users.remove({}, {})
Mongoose: posts.remove({}, {})
Mongoose: users.insertOne({ posts: [], _id: ObjectId("5b0217001b5a55208150cc9b"), firstName: 'Ted', lastName: 'Logan', __v: 0 })
Mongoose: posts.insertOne({ _id: ObjectId("5b0217001b5a55208150cc9c"), user: ObjectId("5b0217001b5a55208150cc9b"), title: 'Hi', body: 'Whoa!', __v: 0 })
Mongoose: users.update({ _id: ObjectId("5b0217001b5a55208150cc9b") }, { '$push': { posts: ObjectId("5b0217001b5a55208150cc9c") } }, {})
userSchema.virtual('posts', {
ref: 'Post',
localField: '_id',
foreignField: 'user'
})
User.aggregate([
{ "$match": { "_id": userId } }
{ "$lookup": {
"from": Post.collection.name,
"localField": "_id",
"foreignField": "user",
"as": "posts"
}}
])