【问题标题】:MongoDb relations not connected with otherMongoDb 关系不与其他关系
【发布时间】:2019-09-04 14:56:44
【问题描述】:

我正在用 node.js 写一本烹饪书。我是这种语言和 mongoDB 概念的新手。我确定我需要一个拥有最喜欢的食谱和最喜欢的食谱的用户我要存储食谱

我的模型看起来像那样,这里有问题

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);
        }
      });
    });
  }

它会保存,但如果我打电话给我的用户,数组收藏夹总是空的

{ favorites: [],
  _id: 5cb32867d2dfea0cadd79ecb,
  name: 'Anna',
  userId:
   'AF322',
  __v: 0 }

我做错了什么?有人可以帮我吗:)

【问题讨论】:

    标签: javascript node.js mongoose nosql mongoose-schema


    【解决方案1】:

    请检查以下代码。我创建了favoritesrecipes 的子模式,使用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}}})
    }
    

    【讨论】:

    • 它不起作用 :( 结果我得到 { ok: 0, n: 0, nModified: 0 }。我不应该使用方法 create 来处理一个新的收藏夹
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-13
    • 2019-03-31
    • 2014-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多