【问题标题】:Creating a Foreign Key relationship in Mongoose在 Mongoose 中创建外键关系
【发布时间】:2014-11-18 10:53:58
【问题描述】:

我从 Mongoose 开始,我想知道如何进行这种类型的配置:

一个食谱有不同的成分。

我有两个模型:

成分和配方:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var IngredientSchema = new Schema({
    name: String
});

module.exports = mongoose.model('Ingredient', IngredientSchema);
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var RecipeSchema = new Schema({
    name: String
});

module.exports = mongoose.model('Recipe', RecipeSchema);

【问题讨论】:

  • 我猜你在问如何使用 Ref 运算符?

标签: node.js mongodb mongoose


【解决方案1】:

检查下面的更新代码,特别是这部分: {type: Schema.Types.ObjectId, ref: 'Ingredient'}

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var IngredientSchema = new Schema({
    name: String
});

module.exports = mongoose.model('Ingredient', IngredientSchema);
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var RecipeSchema = new Schema({
    name: String,
    ingredients:[
      {type: Schema.Types.ObjectId, ref: 'Ingredient'}
    ]
});

module.exports = mongoose.model('Recipe', RecipeSchema);

保存:

var r = new Recipe();

r.name = 'Blah';
r.ingredients.push('mongo id of ingredient');

r.save();

【讨论】:

  • 我如何保存?此刻,我像这样保存: .post(function(req, res) { var recipe = new Recipe(); recipe.name = req.body.name; recipe.save(function(err) { if (err ) res.send(err); res.json({ message: 'recipe created' }); }); })
  • 我试过这个:var ChildSchema = new Schema({ name: String }); mongoose.model('Child', ChildSchema); var ParentSchema = new Schema({ name: String, children: [{ childId: { type: ObjectId, ref: 'Child', required: true } }] }); mongoose.model('Parent', ParentSchema);。当我将孩子推入父文档时,像这样:parent.locations.push({ childId: child.id });parent.save();,文档看起来像这样:{ "name" : "Bob", "children" : [ { "childId" : ObjectId("57769de13eaeda6020b522f2"), "_id" : ObjectId("5776a23a511539a421824c27") } ] }。为什么同时存在childIdid
  • @Web User 您可以将 childId 替换为 _id 或在您的架构中: .... children: [_id:false, { childId: { type: ObjectId, ref: 'Child', required: true } }] 我希望这会有所帮助
  • @John 有多种方法可以做到这一点,John 只是在此处发布另一个问题发布链接,我将尝试回答它,因为这个 cmets 线程越来越大。谢谢
  • @jsh6303 可以在同一个文件中 可以在不同的文件中 没关系。只要它定义并包含
猜你喜欢
  • 2011-12-18
  • 2017-08-29
  • 1970-01-01
  • 2013-03-01
  • 2020-04-04
  • 1970-01-01
  • 2012-08-08
  • 1970-01-01
  • 2021-03-01
相关资源
最近更新 更多