【问题标题】:Save array of ObjectId in Schema在 Schema 中保存 ObjectId 数组
【发布时间】:2014-12-22 01:19:19
【问题描述】:

我有一个名为 Shop 的模型,其架构如下所示:

'use strict';

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

var ShopSchema = new Schema({
  name: { type: String, required: true },
  address: { type: String, required: true },
  description: String,
  stock: { type: Number, default: 100 },
  latitude: { type: Number, required: true },
  longitude: { type: Number, required: true },
  image: String,
  link: String,
  tags: [{ type: Schema.ObjectId, ref: 'Tag' }],
  createdAt: { type: Date, default: Date.now },
  updatedAt: { type: Date, default: Date.now }
});

module.exports = mongoose.model('Shop', ShopSchema);

显然,我想使用数组tags 来通过ObjectId 引用另一个模型。当我通过db.shops.update({...}, {$set: {tags: ...}}) 将 ID 添加到属性中并且 ID 设置正确时,此设置工作正常。但是当我尝试通过分配给模型的 Express.js 控制器执行此操作时,没有任何更新,甚至没有错误消息。这是控制器中的更新功能:

// Updates an existing shop in the DB.
exports.update = function(req, res) {
  if(req.body._id) { delete req.body._id; }
  Shop.findById(req.params.id, function (err, shop) {
    if (err) { return handleError(res, err); }
    if(!shop) { return res.send(404); }
    var updated = _.merge(shop, req.body);
    shop.updatedAt = new Date();
    updated.save(function (err) {
      if (err) { return handleError(res, err); }
      return res.json(200, shop);
    });
  });
};

这适用于Shop 模型的任何其他属性,但不适用于标签。我也尝试将标签的类型设置为字符串,但这没有帮助。

我想我错过了一些关于在 Mongoose 中保存数组的内容?

【问题讨论】:

  • 能否在save 之前给我们举一个updated 对象的示例?
  • 当然,给你:{ _id: 5483977030adcc600450db0f, name: 'Kunstspätkauf', address: 'Schlesische Str. 19, 10997 Berlin', latitude: 52.49861, longitude: 13.446149999999989, image: 'http://www.oushop.com/warp_sites/oushop.g6/files/Shop2.jpg', __v: 0, updatedAt: Sat Dec 06 2014 23:58:13 GMT+0000 (GMT Standard Time), createdAt: Tue Oct 22 2013 10:34:23 GMT+0100 (GMT Daylight Time), tags: [ 5483977030adcc600450db13, 5483977030adcc600450db14 ], stock: 2 }

标签: node.js mongodb mongoose


【解决方案1】:

看起来问题是 _.merge() 无法正确处理合并数组,在您的情况下是 tags 数组。如果可以覆盖现有标签,解决方法是在合并后添加tags 数组的显式分配。

var updated = _.merge(shop, req.body);
if (req.body.tags) {
  updated.tags = req.body.tags;
} 

希望这会有所帮助。如果解决方法不充分,您可以访问lodash 论坛。

【讨论】:

    猜你喜欢
    • 2019-12-09
    • 1970-01-01
    • 2019-08-19
    • 2013-02-06
    • 2015-11-26
    • 2020-04-10
    • 2017-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多