有没有办法更新对象中的值?
{
_id: 1,
name: 'John Smith',
items: [{
id: 1,
name: 'item 1',
value: 'one'
},{
id: 2,
name: 'item 2',
value: 'two'
}]
}
Run Code Online (Sandbox Code Playgroud)
假设我想更新id = 2的项目的名称和值项目;
我尝试了以下w/mongoose:
var update = {name: 'updated item2', value: 'two updated'};
Person.update({'items.id': 2}, {'$set': {'items.$': update}}, function(err) { ...
Run Code Online (Sandbox Code Playgroud)
这种方法的问题在于它更新/设置整个对象,因此在这种情况下我丢失了id字段.
有没有更好的方法在mongoose中设置数组中的某些值但是只留下其他值?
我也只是询问了这个人:
Person.find({...}, function(err, person) {
person.items ..... // I might be able to search through all the items here and find item with id 2 then update the values I want …Run Code Online (Sandbox Code Playgroud) 我试图更新嵌套数组中的值,但无法使其工作.
我的目标是这样的
{
"_id": {
"$oid": "1"
},
"array1": [
{
"_id": "12",
"array2": [
{
"_id": "123",
"answeredBy": [],
},
{
"_id": "124",
"answeredBy": [],
}
],
}
]
}
Run Code Online (Sandbox Code Playgroud)
我需要将值推送到"answersBy"数组.
在下面的例子中,我尝试将"success"字符串推送到"123 _id"对象的"answersBy"数组,但它不起作用.
callback = function(err,value){
if(err){
res.send(err);
}else{
res.send(value);
}
};
conditions = {
"_id": 1,
"array1._id": 12,
"array2._id": 123
};
updates = {
$push: {
"array2.$.answeredBy": "success"
}
};
options = {
upsert: true
};
Model.update(conditions, updates, options, callback);
Run Code Online (Sandbox Code Playgroud)
我找到了这个链接,但它的答案只说我应该使用类似对象的结构而不是数组.这不适用于我的情况.我真的需要我的对象嵌套在数组中
如果你能在这里帮助我会很棒.我花了好几个小时来搞清楚这一点.
先感谢您!
我有以下文件:
{
"_id" : ObjectId("503b83dfad79cc8d26000004"),
"pdfs" : [
{
"title" : "Test document",
"pdf_id" : ObjectId("504f6793ce351a595d000004"),
"created_at" : ISODate("2012-09-11T16:32:19.276Z")
},
{
"title" : "Some other doc",
"pdf_id" : ObjectId("502bf124b4642341230003f0"),
"created_at" : ISODate("2012-09-11T11:34:19.276Z")
}
]
}
Run Code Online (Sandbox Code Playgroud)
现在在传入的表单中req.body,我有2个字段:title和description.
我想更新title并插入description指定的pdf_id,我该怎么做?
所以最后,我的文档现在看起来像:
{
"_id" : ObjectId("503b83dfad79cc8d26000004"),
"pdfs" : [
{
"title" : "This is an UPDATED title",
"description" : "It has an ALL NEW description",
"pdf_id" : ObjectId("504f6793ce351a595d000004"),
"created_at" : ISODate("2012-09-11T16:32:19.276Z")
},
{
"title" …Run Code Online (Sandbox Code Playgroud)