我用的是mongoose,代码是这样写的:
MODEL("Articl").articles.update({
_id : id
}, {
$push : {
comment : data
}
}, {
upsert : true
}, function (err, result) {})
我知道upsert:true存在问题,但我想知道为什么被恶意插入的document的 _id为null, 求可能存在的情况,谢谢大家!
6 回复
@DoubleSpout 插入的document中,data包含了一个**_id**,就是外面的没有,下面为插入后的数据:
{
_id : null,
comment : [{
_id : "54b9b077526961a141e4611f",
content : ""
}
],
createtime : "2015-01-17T01:59:49.533Z"
}
@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 } ] } ]
})
})
})