Meteor/MongoDB 更新所有输入字段
Meteor/MongoDB update all fields for entry
我在 Meteor 中使用 Mongo 并编写了一个基本的 CRUD,但想知道是否可以更新条目中的所有字段。我似乎只能更新条目中的特定字段,如下所示:
Brief.update(briefObject._id, { $set: { description: briefObject.description} });
是否可以通过传入整个对象来更新整个条目?我试图让我的代码保持干燥,而不必编写不同的函数来更新条目的不同字段。像这样:
Brief.update(brief._id, { $set: briefObject }
这是条目示例的输出:
meteor:PRIMARY> schema = db.briefs.findOne();
{
"_id" : "a56xpJ3ZTAzZKFmwD",
"title" : "Foo",
"client" : "Bar",
"deadline" : ISODate("2017-01-01T12:00:00Z"),
"description" : "Lorem Ipsum Dolor Sit",
"createdAt" : ISODate("2016-01-15T16:20:46.403Z"),
"username" : "fooBar"
}
这是 briefObject
的示例:
{ title: 'Foo',
client: 'Bar',
deadline: Sun Jan 01 2017 12:00:00 GMT+0000 (GMT),
description: 'Lorem Ipsum Dolor Sit Amet',
createdAt: Fri Jan 15 2016 16:20:46 GMT+0000 (GMT),
username: 'fooBar',
_id: 'a56xpJ3ZTAzZKFmwD',
'$$hashKey': 'object:4'
}
您可以通过在使用前删除其他两个键 _id
和 $$hashKey
来重新创建要在 $set
运算符中使用的更新对象它在更新中。使用这种方法,您不必重新创建对象中的所有属性,只需从新对象中删除保留键即可。
您可以创建可在 update
中使用的选择器和修饰符对象,如下例所示:
var selector = { "_id": briefObject._id },
modifier = { "$set": briefObject };
delete modifier["$set"]["_id"];
delete modifier["$set"]["$$hashKey"];
Brief.update(selector, modifier);
我在 Meteor 中使用 Mongo 并编写了一个基本的 CRUD,但想知道是否可以更新条目中的所有字段。我似乎只能更新条目中的特定字段,如下所示:
Brief.update(briefObject._id, { $set: { description: briefObject.description} });
是否可以通过传入整个对象来更新整个条目?我试图让我的代码保持干燥,而不必编写不同的函数来更新条目的不同字段。像这样:
Brief.update(brief._id, { $set: briefObject }
这是条目示例的输出:
meteor:PRIMARY> schema = db.briefs.findOne();
{
"_id" : "a56xpJ3ZTAzZKFmwD",
"title" : "Foo",
"client" : "Bar",
"deadline" : ISODate("2017-01-01T12:00:00Z"),
"description" : "Lorem Ipsum Dolor Sit",
"createdAt" : ISODate("2016-01-15T16:20:46.403Z"),
"username" : "fooBar"
}
这是 briefObject
的示例:
{ title: 'Foo',
client: 'Bar',
deadline: Sun Jan 01 2017 12:00:00 GMT+0000 (GMT),
description: 'Lorem Ipsum Dolor Sit Amet',
createdAt: Fri Jan 15 2016 16:20:46 GMT+0000 (GMT),
username: 'fooBar',
_id: 'a56xpJ3ZTAzZKFmwD',
'$$hashKey': 'object:4'
}
您可以通过在使用前删除其他两个键 _id
和 $$hashKey
来重新创建要在 $set
运算符中使用的更新对象它在更新中。使用这种方法,您不必重新创建对象中的所有属性,只需从新对象中删除保留键即可。
您可以创建可在 update
中使用的选择器和修饰符对象,如下例所示:
var selector = { "_id": briefObject._id },
modifier = { "$set": briefObject };
delete modifier["$set"]["_id"];
delete modifier["$set"]["$$hashKey"];
Brief.update(selector, modifier);