使用Mongoose更新对象数组

时间:2017-12-12 16:22:24

标签: mongodb express mongoose

我正在尝试更新模型上的对象数组,Stuff。

我的模特:

var StuffSchema = new Schema({
  name: { type: String, required: true },
  things: [Object]
});

在我的路线中:

Stuff.update({"_id": req.params.id}), {$push: {"things": {$each: req.body.things}}}, function(err, raw) {
  console.log(raw);
  if (err) throw err;
  res.json(true);
})

这会引发错误:

Error: No default engine was specified and no extension was provided.

console.log的输出是:

{ ok: 0, n: 0, nModified: 0 }

对一组对象进行硬编码会得到相同的结果:

Stuff.update({"_id": req.params.id}), {$push: {"things": {$each: [{a: 1, b: 2}, {a: 3, b: 4}]}}}, function(err, raw) {
  console.log(raw);
  if (err) throw err;
  res.json(true);
})

但是,如果我只是更新名称字段:

Stuff.update({"_id": req.params.id}), {"name": "fancy pants"}, function(err, raw) {
  console.log(raw);
  if (err) throw err;
  res.json(true);
})

这正确地更新了Stuff文档,console.log的输出是:

{ n: 1, nModified: 0, opTime: { ts: Timestamp { _bsontype: 'Timestamp', low_: 1, high_: 1513093848 }, t: 1 }, electionId: 7fffffff0000000000000001, ok: 1 }

我错过了什么?

1 个答案:

答案 0 :(得分:1)

错误No default engine was specified and no extension was provided表示当您要渲染视图时,您必须至少提供一个包含其扩展名的文件:

res.render('index.html');

设置默认视图引擎,如下所示:

app.set('view engine', 'pug');

同样在StuffSchema更改Object类型为Mixed

var StuffSchema = new Schema({
    name: { type: String, required: true },
    things: [Schema.Types.Mixed]
});