如何把这段mongoose缩减得更加优美?
发布于 6 年前 作者 DoubleCG 3616 次浏览 来自 问答

听说有一个方法是如果已经有了相同的结果,则不更新.

	Friendlink.find(
		{
			linkname: new_linkname
		},
		null,
		{
			limit: 1
		},
		function(err,result){
			if(err) throw err;
			if(result.length){
				res.send('相同的链接名已经存在!');
			}else{
				Friendlink.update(
					{
						linkname: initial_linkname
					},
					{
						linkname: new_linkname, 
						linkurl: new_linkurl
					},
					{
						upsert: true
					},
					function(err){
						if(err) throw err;
						res.send('Success to Update!');
					}
				);
			}
		}
	);
6 回复

我觉得你可以把 update 这个function 提出来,在find 不到相同之后调这个 update function 应该看起来好看一点,而且你是不是find 这个function写错了?少了一个 逗号吧。

findOneAndUpdate 是查找到某个东西然后对其更新

Upsert Option If updateOne(), updateMany(), or replaceOne() includes upsert : true and no documents match the specified filter, then the operation creates a new document and inserts it. If there are matching documents, then the operation modifies or replaces the matching document or documents.

For details on the new document created, see the individual reference pages for the methods. mongodb的, 应该也适用mongoose。。。 await 用起来比啥都好看!!!

@hewentaowx 是的,已更正。

@lzszone 开始摸到 async 了!

回到顶部