所以我正在使用nodeJS
和mongoDB
。我在更新收藏时遇到问题,自从我开始处理它以来已经一周了,这确实让我头疼。这是我的示例集合
{
"_id": ObjectId('51299sdfasdf') //this is just a sample Id
"names": [
"NameA",
"NameB",
"NameC"
],
"names_id": [
ObjectId('asdfasdf1312'),
ObjectId('12sda123123a'),
ObjectId('asdf1212123a')
],
"user_alias": "SampleA"
}
这是我的脚本
var mongoose = require('mongoose');
var model = mongoose.model('Sample');
model.update( { _id: req.query._id },
{
$set: {
names: namesArray, //this are set of names ex; ['name1', 'name2']
names_id: namesIdArray //this are set of ids ex: [ ObjectId('sgsdfgsd'), ObjectId('asdfasdfadf')
},
},
function(err, results) {
if(err) res.status(500).send(err);
console.log(results);
}
);
我知道我的代码是正确的。在names_id数组中,我指定了所有对象ID,例如mongoose.mongo.ObjectId('id here')
。但它没有更新任何东西。这是结果。
{ ok: 1, nModified: 0, n: 1 }
这里有什么问题吗?这是版本的原因吗?我的 mongoose
版本是 2.15.8
请帮帮我!谢谢!
最佳答案
别那么沮丧, Mongoose 没有任何问题, 我认为你的问题是因为 req.query.id 是一个字符串 您需要首先将字符串转换为ObjectId
文档未更新,因为它没有找到任何文档,没有其他原因,只需将 _id 转换为对象 id
阅读此内容可将 Id 转换为 object Id Convert string to ObjectID in MongoDB
关于node.js - $set 不适用于 mongodb 更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40436401/