[英]MongoDB insert record issue
I have a Mongo DB structure which looks something like this : 我有一个Mongo DB结构,看起来像这样:
db.users.find().pretty();
{
"_id" : ObjectId("52b42b148ffa91f7ebbe8ebc"),
"username" : "test",
"password" : "test",
"party" : [
"4988",
"5037"
],
"something" : [
"3571"
],
"ludilo" : [],
}
Im using express js in my app and this module for connecting to Mongo https://npmjs.org/package/mongodb , 我在我的应用程序和本模块中使用快速js连接到Mongo https://npmjs.org/package/mongodb ,
How can I insert one entry into "something" array for user with id that I get from session. 如何为具有我从会话获得的id的用户插入一个条目到“something”数组。
I tried something like this , but with no success 我试过这样的事,但没有成功
var collection = db.collection('users');
collection.find({'_id':new ObjectID(req.user.id)}).toArray(function(err, items) {
console.dir(items);
}).insert({"something":"1234"});
You can $push
a value to an array with 您可以使用$push
值$push
送到数组
db.users.update(
{ _id: ObjectId( "52b42b148ffa91f7ebbe8ebc" ) },
{ $push: { something: "1234" } }
)
or if you do not want any duplicates in your array you can use $addToSet
或者如果您不希望阵列中有任何重复项,则可以使用$addToSet
db.users.update(
{ _id: ObjectId( "52b42b148ffa91f7ebbe8ebc" ) },
{ $addToSet: { something: "1234" } }
)
You can try this code: 你可以试试这段代码:
collection.find({_id: new ObjectID(req.user.id)}).toArray(function(err, items) {
var doc = items[0];
doc.something.push('1234');
collection.update({_id: doc._id}, {$set: {something: doc.something}}, {safe: true}, function() {
//your next actions
});
});
I run this code on my local machine and it seems to work fine 我在我的本地机器上运行此代码,它似乎工作正常
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.