Node.js 首先加载特定的猫鼬模型
我试图在我的“like”模型类(下面的代码)中使用一个模型(“目标”)。但是,每次启动节点实例时,它都会说Node.js 首先加载特定的猫鼬模型,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,我试图在我的“like”模型类(下面的代码)中使用一个模型(“目标”)。但是,每次启动节点实例时,它都会说Goal.findById不是一个函数 在每个模型中运行了一个console.log(number)之后,我发现它们的加载非常奇怪,并且不符合我想要/需要的顺序 我想知道如何在其他模型之前加载模型,或者为模型设置特定的加载顺序 var mongoose = require('mongoose'); var Schema = mongoose.Schema; var User = requir
Goal.findById
不是一个函数
在每个模型中运行了一个console.log(number)之后,我发现它们的加载非常奇怪,并且不符合我想要/需要的顺序
我想知道如何在其他模型之前加载模型,或者为模型设置特定的加载顺序
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var User = require('../models/user.js');
var Goal = require('../models/goal.js');
var likeSchema = new Schema({
userPosted: {
type: Number,
ref: 'user',
required: true
},
goal: {
type: Number,
ref: 'goal',
required: true
}},
{
timestamps: true
});
likeSchema.post('save', function (doc, next) {
var goalID = doc.goal;
Goal.findOne({'_id': doc.goal}, function(err, goal) {
goal.likes.push(doc._id);
goal.save();
User.findById(doc.userPosted, function(err, user) {
user.likedPosts.push(goalID);
user.save();
next();
});
});
});
likeSchema.post('remove', function(doc) {
Goal.findById(doc.goal, function(err, goal) {
goal.likes.pull(doc._id);
goal.save();
User.findById(doc.userPosted, function(err, user) {
user.likedPosts.pull(goal._id);
user.save();
});
});
});
console.log("4");
module.exports = mongoose.model('like', likeSchema);
错误:
TypeError: Goal.findOne is not a function at model.<anonymous> (E:\Project\like.js:28:10)
我想你的
像chema
会是这样的-
var likeSchema = new Schema({
userPosted: {
type: Number,
ref: 'User',
required: true
},
goal: {
type: Number,
ref: 'Goal',
required: true
}},
{
timestamps: true
});
如果它不起作用,你能展示你的
目标
模型的代码吗?我想你的likeschema
应该是这样的-
var likeSchema = new Schema({
userPosted: {
type: Number,
ref: 'User',
required: true
},
goal: {
type: Number,
ref: 'Goal',
required: true
}},
{
timestamps: true
});
如果它不起作用,请显示
Goal
model的代码。您是否正确地将Goal.js文件“导出”为模块?@NidhinDavid-oh-yes。很抱歉,我没有包括这些,但我有。在尝试使用之前,您需要确保所有模型都已定义。你能展示一下goal.js的代码吗?@Molda添加到post我认为你应该做的是定义模式,然后导出模型,然后在模式中添加pre和post钩子,或者甚至不使用钩子,而是创建自定义函数来做你想做的事情。你是否正确地将goal.js文件“导出”为模块?@NidhinDavid-oh是的。很抱歉,我没有包括这些,但我有。在尝试使用之前,您需要确保所有模型都已定义。你能展示一下goal.js的代码吗?@Molda添加到post我认为你应该做的是定义模式,然后导出模型,然后在模式中添加pre和post钩子,或者甚至不使用钩子,而是创建自定义函数来做你想做的事情。错误实际上是在pre和post中间件中,它说goal.findOne不是一个函数。我发现这是因为目标模型还没有加载。错误实际上是在前置和后置中间件中,它说Goal.findOne不是一个函数。我发现这是因为目标模型尚未加载。