Article.findByIdAndUpdate(req.body.aid,{$set:{title:req.body.title,tags:req.body.tags,uid:req.body.uid,pv:req.body.pv}},function(err,Article){
if(!err){
if(!req.body.article){
Article.findByIdAndUpdate(Article._id,{$push:{Article:{collections:{
uid: req.body.uid,
time: req.body.time,
article: req.body.article.split("<!--p-->"),
}}}},function(err,Article){
if(!err){
res.send('数据更新成功')
}
});
}
res.send('数据更新成功')
}
});
{
"uid" : "4hg56f4hf",
"title" : "f5sdf456sd",
"tags" : "dfs,f,s,sdg,ds,gs,g,s,dg",
"pv" : 0,
"_id" : ObjectId("52da4efb5007465c1c16006e"),
"comments" : [],
"collections" : [{
"uid" : "4hg56f4hf",
"time" : new Date("2/1/1970 18:17:36"),
"_id" : ObjectId("52da4efb5007465c1c16006f"),
"article" : ["j4f5gh4564h\\r\\nf5<!--page-->6sd4f564sf6h4s64h6sdhsh56sd26dsh56sh65s6+h56+sd5h5sd6+h56+<!--page-->sd5gf65f6h5fg6j4f4h5kjh54jh5f4f418451544156154845oiuyyurjkjhgfsdadfghjkjhgfdsasdfghjklkjhgfd"]
}],
"__v" : 0
}
##怎么在collections数组中添加一个集
{
uid: req.body.uid,
time: req.body.time,
article: req.body.article.split("<!--p-->"),
}
楼主我现在也遇到这个问题,请问下,你是怎么解决的?
貌似没解决好像~
你查出来以后,找到collections节点添加节点,再存进去。 --------------------贴段代码可以参考一下---------------------- collection.findOne(user,function(err,value){ if(err) next(err); // console.log(value); //第一次添加数据到myTweetList集合中。需要创建一个对象 if(value == undefined || value == null){ // var insert_obj = obj; db.collection(collection_name,function(err,collection){ collection.insert(obj,{safe:safe},function(err,result){ // console.log('insert err = '+err+'value = '+value); next(err,result); }) }) }else{ //已经有数据了,需要更新数据 if(value.tweetlist == undefined || value.tweetlist == null){ value.tweetlist = new Array(); } for(var i = 0 ,length = obj.tweetlist.length;i<length ;i++){ var _u = { ‘tweetname’:obj.tweetlist[i].tweetname, ‘password’:obj.tweetlist[i].password }; value.tweetlist.push(_u); } db.collection(collection_name,function(err,collection){ collection.update(user,value,{safe:safe},function(err){ next(err,value); }) }) } })
好像可以通过 $push或者 $addToSet进行操作数组集合 通过mongoDB直接操作,例子: > db.blog.update({“title”:“one blog”}, {"$push": {“comments”:{“content”:“word”}} > db.blog.findOne() { "_id" : ObjectId(“4fcd909520668578cc1097dc”), “comments” : [ { “content” : “hello” }, { “content” : “word” } ], “title” : “one blog” }