Mongodb被恶意插入一条数据,但_id却为null
发布于 9 年前 作者 satrong 4799 次浏览 最后一次编辑是 8 年前 来自 问答

我用的是mongoose,代码是这样写的:

MODEL("Articl").articles.update({
	_id : id
}, {
	$push : {
		comment : data
	}
}, {
	upsert : true
}, function (err, result) {})

我知道upsert:true存在问题,但我想知道为什么被恶意插入的document的 _id为null, 求可能存在的情况,谢谢大家!

6 回复

data里包含了 **_id * 这个key吧

@DoubleSpout 插入的document中,data包含了一个**_id**,就是外面的没有,下面为插入后的数据:

{
	_id : null,
	comment : [{
			_id : "54b9b077526961a141e4611f",
			content : ""
		}
	],
	createtime : "2015-01-17T01:59:49.533Z"
}

想知道前面:

MODEL("Articl").articles

是怎麼發生的?

@chinghanho 定义的一个schema:

var schma = mongoose.Schema({
    title: {
        type: String,
        trim: true,
        length: 40
    },
    createtime: {
        type: Date,
        default: Date.now,
        unique: true
    },
    comment: [
        {
			username:String
            content:String
        }
    ]
});

exports.articles = mongoose.model("articles", schma);

我嘗試照個做了一次,沒有發生這個問題,你看看:

var mongoose = require('mongoose')

mongoose.connect('mongodb://localhost:27017/test')

var ArticleSchema = new mongoose.Schema({
  comments: [{
    username: { type: String },
    content: { type: String }
  }]
})

mongoose.model('Article', ArticleSchema)

var Article = mongoose.model('Article')

var comment = {
  username: 'chh',
  content: 'hello world'
}

Article.create({
  comments: [ comment ]
},

function (err, article) {

  if (err) return console.log(err)

  Article.update(
    { _id: article._id },
    { $push: { comments: { username: 'david', content: 'foobar' } } },
    { upsert : true },

  function () {
    Article.find({ _id: article._id }).exec(function (err, articles) {
      console.log(articles)

      // [ { _id: 54b9e6ca6426ef590d317a56,
      //     __v: 0,
      //     comments: 
      //      [ { username: 'chh',
      //          content: 'hello world',
      //          _id: 54b9e6ca6426ef590d317a57 },
      //        { content: 'foobar',
      //          username: 'jobs',
      //          _id: 54b9e6ca6426ef590d317a58 } ] } ]

    })
  })

})

@chinghanho 是啊,我也尝试了好多次了,不知道别人是怎么恶意插入的

回到顶部