简体   繁体   English

在猫鼬中保存一对多的关系双方

[英]Saving one-to-many relationships in Mongoose both sides

I am very new to MongoDB and am using Mongoose.我对 MongoDB 很陌生,正在使用 Mongoose。

I have two models: users and recipes .我有两个模型: usersrecipes

User : User

recipes: [{
    type: Schema.Types.ObjectId,
    ref: 'recipes'
}],

Recipe : Recipe

_creator: {
    type: Schema.Types.ObjectId,
    ref: 'User',
    childPath: "recipes"
},

When I try to save a recipe and I assign the user to a recipe:当我尝试保存食谱并将用户分配给食谱时:

var recipe = new models.Recipe({
        title: req.body.title,
        slug: req.body.slug,
        _creator: user._id
    });

    recipe.save();

The recipe gets saved just fine ( even though I am not able to do recipe._creator.name to get the user name from the recipe ).配方保存得很好(即使我无法使用 recipe._creator.name 从配方中获取用户名)。 But if I try to get the user details, the recipes array is empty.但是,如果我尝试获取用户详细信息,则recipes数组为空。 I would expect that it was filled with the newly created recipe reference.我希望它充满了新创建的配方参考。 Why is it not?为什么不是?

if i understand correctly one creator has many recipes.如果我理解正确的话,一位创作者有很多食谱。 right ?对吗? in that case your creator should recipes should reference have a reference to creator that's it.在这种情况下,你的创作者应该食谱应该引用对创作者的引用,就是这样。

if you examine closely in recipes you are doing a ref on recipes itself如果您仔细检查食谱,您就是在参考食谱本身

{ recipes: [{
    type: Schema.Types.ObjectId,
    ref: 'recipes'
}],

}

instead you should do相反,你应该做

{
    { recipes: [{
        type: Schema.Types.ObjectId,
        ref: 'user'
    }],
}

why in your user model you have a reference to user itself ?为什么在你的用户模型中你有对用户本身的引用? that seems not right.这似乎不对。

check for an example i posted on Mongodb and Express检查我在Mongodb 和 Express上发布的示例

I had the same issue, what I had done to resolve this was updating both documents with the corresponding reference我遇到了同样的问题,我为解决这个问题所做的是使用相应的参考更新两个文档

 var recipe = new models.Recipe({ title: req.body.title, slug: req.body.slug, _creator: user._id }); recipe.save((err) => { if (err) { console.log(err); } user.recipes.push(recipe); user.save(); });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM