Mongodb 使用Mongoose更新对象数组
我正在尝试更新模型上的一组对象,等等 我的模型:Mongodb 使用Mongoose更新对象数组,mongodb,express,mongoose,Mongodb,Express,Mongoose,我正在尝试更新模型上的一组对象,等等 我的模型: 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(
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);
})
这将抛出错误:
错误:未指定默认引擎,也未提供扩展。
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{{u bsontype:'Timestamp',低uu∶1,高∶1513093848},t:1},electionId:7fffffff000000000000001,ok:1}
我缺少什么?错误
未指定默认引擎且未提供扩展名
意味着当您要渲染视图时,必须至少提供一个文件及其扩展名:
res.render('index.html');
或设置默认视图引擎,如下所示:
app.set('view engine', 'pug');
另外,在StuffSchema
中,将对象更改为Mixed
:
var StuffSchema = new Schema({
name: { type: String, required: true },
things: [Schema.Types.Mixed]
});
切换到Schema.Types.Mixed
成功了!Mongoose文档声称Schema.Types.Mixed
、Object
和{}
是等价的,但显然不是这样。