【发布时间】: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 }