gpt4 book ai didi

node.js - 简单 mongo/monk findAndModify 查询的问题

转载 作者:太空宇宙 更新时间:2023-11-03 23:07:04 24 4
gpt4 key购买 nike

请注意,我对 mongo 相当陌生,尤其是对使用 Node/js 非常陌生。

我正在尝试编写一个查询来插入新文档或更新我的集合中已有的文档。

建议的集合结构是:

{ _id: xxxxxxx, ip: "xxx.xxx.xxx.xxx:xxxxxx", 日期: "xx-xx-xx xxxx"}

请注意,我的意图是为 _id 存储固定长度的 int,而不是内部 ObjectId(这可能/被认为是不好的做法吗?)。 int 保证是唯一的并且来自另一个来源。

var monk = require('monk');
var db = monk('localhost:27017/cgo_schedule');

var insertDocuments = function(db, match) {
var db = db;
var collection = db.get('cgo_schedule');
collection.findAndModify(
{
"query": { "_id": match.matchId },
"update": { "$set": {
"ip": match.ip,
"date": match.date
},
"$setOnInsert": {
"_id": match.matchId,
}},
"options": { "new": true, "upsert": true }
},
function(err,doc) {
if (err) throw err;
console.log( doc );
}
);
}

但这根本不起作用。它不会向数据库插入任何内容,但也不会给出任何错误,所以我不知道我做错了什么。

输出(console.log (doc))为空。

我做错了什么?

最佳答案

Monk 文档没有太大帮助,但根据 source codeoptions 对象必须作为单独的参数提供。

因此您的调用应如下所示:

collection.findAndModify(
{
"query": { "_id": match.matchId },
"update": {
"$set": {
"ip": match.ip,
"date": match.date
}
}
},
{ "new": true, "upsert": true },
function(err,doc) {
if (err) throw err;
console.log( doc );
}
);

请注意,我删除了 $setOnInsert 部分,因为 _id 始终包含在带有 upsert 的插入中。

关于node.js - 简单 mongo/monk findAndModify 查询的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31529471/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com