node.js - Save array of ObjectId in Schema -
i have model called shop
whos schema looks this:
'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);
i want use array tags
reference model via objectid
obviously. set works fine when add ids property via db.shops.update({...}, {$set: {tags: ...}})
, ids set properly. when try via express.js controller assigned model, nothing gets updated , there no error message. here update function in controller:
// updates existing shop in 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); }); }); };
this works perfect other properties of shop
model not tags. tried set type of tags string, didn't help.
i guess missing saving arrays in mongoose?
it looks issue _.merge()
cannot handle merging arrays properly, tags
array in case. workaround adding explicit assignment of tags
array after merge, if ok overwrite existing tags.
var updated = _.merge(shop, req.body); if (req.body.tags) { updated.tags = req.body.tags; }
hope helps.. if workaround not sufficient may visit lodash
forums.
Comments
Post a Comment