我正在node.js中写一本烹饪书。我是这种语言和mongoDB概念的新手。我确定我需要一个在我要存储食谱的最喜欢食谱中具有最喜欢食谱的用户
我的模型看起来像这样,这里有些问题
int num1,num2,temp;
printf("give no 1 and no 2 ");
scanf("%d %d",&num1, &num2);
num1=temp;
temp=num2;
num2=num1;
printf("\n After swapping,num1=%d" ,num1);
printf("\n afterswapping, num2=%d",num2);
我写了一个寻找用户然后存储喜欢的食谱的函数
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
userSchema = new Schema({
name: String,
userId: {type: String, required: true},
favorites: [{
type: Schema.Types.ObjectId,
ref: 'Favorites',
}],
});
favoritesSchema = new Schema({
name: String,
id: {type: Schema.Types.ObjectId},
recipes: [{
type: Schema.Types.ObjectId,
ref: 'Recipes',
}],
startOfRecipe: {type: Date},
});
recipeSchema = new Schema({
name: {type: String, unique: true},
});
const User = mongoose.model('User', userSchema);
const Favorites = mongoose.model('Favorites', favoritesSchema);
const Recipes = mongoose.model('Recipes', recipeSchema);
module.exports = {User, Favorites, Recipes};
它会保存,但是如果我给用户打电话,则数组收藏夹始终为空
addFav(fav, userId) {
return new Promise(function(resolve, reject) {
schema.User.findOne({userId: userId}, function(err, user) {
if (err || !user) {
} else {
schema.Favorites.create({
name: fav,
}, (err, result) => {
if (err) throw err;
console.log(result);
resolve('noResult');
});
resolve(user);
}
});
});
}
我在做什么错?有人可以帮我吗:)
答案 0 :(得分:0)
请检查以下代码。我创建了favorites
和recipes
的子模式,使用userId
获取用户详细信息,并将favorites
对象推入favorites
字段
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
userSchema = new Schema({
name: String,
userId: {type: String, required: true},
favorites: [favoritesSchema],
});
favoritesSchema = new Schema({
name: String,
id: {type: Schema.Types.ObjectId},
recipes: [recipeSchema],
startOfRecipe: {type: Date},
});
recipeSchema = new Schema({
name: {type: String, unique: true},
});
const User = mongoose.model('User', userSchema);
addFav(fav, userId) {
return Schema.User.update({_id:userId}, {$set:{$push:{favorites:fav}}})
}