Node.js 在MongoDB中检索更新后的子文档ID
我编写了一个服务,使用update语句将新数据推送到我的集合中,我需要检索上次插入数据的id。我正在为此使用Node.js 在MongoDB中检索更新后的子文档ID,node.js,mongodb,mongoose,mongodb-query,Node.js,Mongodb,Mongoose,Mongodb Query,我编写了一个服务,使用update语句将新数据推送到我的集合中,我需要检索上次插入数据的id。我正在为此使用db.collection.update,但它只是给出如下响应: { "result": { "ok": 1, "nModified": 1, "n": 1 } } 我的api是: app.post('/feeds',function(req,res) { var _id = req.body._id; var title
db.collection.update
,但它只是给出如下响应:
{
"result": {
"ok": 1,
"nModified": 1,
"n": 1
}
}
我的api是:
app.post('/feeds',function(req,res) {
var _id = req.body._id;
var title = req.body.title;
var description = req.body.description;
var latitude = Number(req.body.latitude);
var longitude = Number(req.body.longitude);
db.user.update(
{_id:_id },
{$push : {
feed:{
title: title,
description:description,
latitude:latitude,
longitude:longitude
}
}
},function (err,result) {
if (err) {
res.json({"success": '0', "message": "Error adding data"});
}
else {
res.json({'result':result});
}
});
});
这是我的猫鼬模式:
var user = new mongoose.Schema({
username : {type: String},
email : {type: String,index: {unique: true}},
password : {type: String},
feed : [{
title : {type: String},
description : {type: String},
latitude : {type:Number},
longitude : {type:Number},
feedImages : [{
imageUrl: {type: String}
}],
}]
});
我想向提要添加数据
我的数据库结构
我需要新推送提要的id。您应该使用
db.user.insert()
,既然您已经从req正文中获得了id,为什么还需要它
db.user.insert(objectToInsert, function(err,docsInserted){
console.log(docsInserted);
});
嵌入方式(当前模式)
如果希望每个提要使用一个文档并将子文档推入(嵌入方式),则可以将\u id
预先分配给新创建的提要子文档
:
var feedId = new ObjectId();
db.user.update({
_id: _id
}, {
$push: {
feed: {
_id: feedId,
title: title,
description: description,
latitude: latitude,
longitude: longitude
}
}
}, function(err, result) {
/* ...your code... */
});
如果要查询此字段,请不要忘记为user.feed.\u id
添加索引(使用ensureIndex
或createIndex
,具体取决于您的版本)
使用单独的集合
作为替代方法,您可以使用一个单独的提要集合,并使用包含userId
外键的insert
语句
您可以通过使用找到更多关于赞成/反对的信息。这是一个很好的例子
查找匹配的文档,根据更新参数进行更新,传递任何选项,并将找到的文档(如果有)返回回调。如果通过回调,查询将立即执行
可用选项
new:bool-如果为true,则返回修改后的文档,而不是原始文档。默认值为false(在4.0中更改)
您正在尝试插入新记录或尝试更新现有记录?更新时将没有新推送源的任何id可用。否,推送数据时正在生成id。但问题在于检索。当我使用insert时,我可以在数据库中看到Id显示错误:TypeError:undefined不是一个函数。我理解这个问题,他想获取子文档的Id,而不是文档的Id(他已经知道)。@str:他将获取整个文档,包括子文档及其Id。。。。并且必须过滤大量可能有重复项的子文档。不理想。@str:同意。预分配ID似乎是最好的。不过,这是次好的选择。:)