node.js 在 mongoose 中保存时带有 ObjectId 的参考文档

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16700563/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:34:16  来源:igfitidea点击:

Reference documents with ObjectId when saving in mongoose

node.jsmongodbexpressmongoose

提问by gmajivu

I have the following schemas:

我有以下模式:

// ingredient
var ingredSchema = new Schema({
  name: String,
  cost: Number
});

// order
var orderSchema = new Schema({
  cusName: String,
  ingredients: [{type: Schema.Types.ObjectId, ref: 'Ingredient'}]
});

// create model
var Ingredient = mongoose.model('Ingredient', ingredSchema);
var Order = mongoose.model('Order', orderSchema);

I have already saved a bunch ingredients in a collection ingredientsand have a UI where users choose a set of ingredients for their burgers. I then try to save an order for a burger in another collection orderswithin the same database burgerslike this:

我已经在一个集合中保存了一堆配料,ingredients并有一个用户界面,用户可以在其中为他们的汉堡选择一组配料。然后我尝试orders在同一个数据库中的另一个集合中保存一个汉堡的订单,burgers如下所示:

// get order info from the form
var newOrder = new Order({ cusName: req.body.name, 
                           ingredients: req.body.ingredients });
newOrder.save(function(err) {
    if (err)
        return console.log('Could not save your new order', err);
    res.redirect('/order');
});

The call to save an order generates the following error:

保存订单的调用会产生以下错误:

{ message: Cast to ObjectId failed for value xxx at path 'ingredients',
  name: 'CastError',
  type: ObjectId,
  value: xxx,
  path: 'ingredients' }

I use mongoose version 3.6.11. Please help me hack this.

我使用猫鼬版本 3.6.11。请帮我破解这个。

PS: req.body.ingredients is an array built from checkboxes.

PS:req.body.ingredients 是一个由复选框构建的数组。

采纳答案by gustavohenke

There are 2 possible problems with your code right now:

您的代码现在有两个可能的问题:

1. req.body.ingredientswill not be an array of ObjectIds, and mongoose wants it alright (I doubt of this one).

1.req.body.ingredients不会是ObjectIds的数组,猫鼬想要它好(我怀疑这个)。

You should cast every ingredient to ObjectIdfirst. Supposing req.body.ingredientsis array, then you would do something like this:

你应该把每一种成分都ObjectId放在第一位。假设req.body.ingredients是数组,那么你会做这样的事情:

var casted = req.body.ingredients.map(function( ingredient ) {
  return mongoose.Types.ObjectId(ingredient);
});

I did not tested this, see if it'll work for you.

我没有测试过这个,看看它是否适合你。

2. Mongoose is trying to cast your ingredients, but one of them is not a valid ObjectId

2. Mongoose 正在尝试铸造您的成分,但其​​中之一无效 ObjectId

ObjectIdshould be composed of 24 hex chars, check whether you're passing values like this to Mongoose.

ObjectId应该由 24 个十六进制字符组成,检查您是否将这样的值传递给猫鼬。



Please, post the result if one of them work for you :)

如果其中之一适合您,请发布结果:)